Skip to content

jsonObject

A simple wrapper for mysql's JSON_OBJECT. This also allows nested object with a user-friendly syntax


Demo

Simple json object

js
const result = knex('users')
  .select({
    users: knex.jsonObject({
      id: 'users.id'
    })
  })
  .toString()
sql
const expected = 'select JSON_OBJECT("id", users.id) as `users` from `users`'

Simple json object with two properties

js
const result = knex('users')
  .select({
    users: knex.jsonObject({
      id: 'users.id',
      name: 'users.name'
    })
  })
  .toString()
sql
const expected = 'select JSON_OBJECT("id", users.id, "name", users.name) as `users` from `users`'

Nested json object

js
const result = knex('users')
  .select({
    users: knex.jsonObject({
      id: 'users.id',
      name: 'users.name',
      parents: knex.jsonObject({
        id: 'parents.id',
        name: 'parents.name'
      })
    })
  })
  .toString()
sql
const expected = 'select JSON_OBJECT("id", users.id, "name", users.name, "parents", JSON_OBJECT("id", parents.id, "name", parents.name)) as `users` from `users`'