Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

257
Vistas
Postgresql: How do I use dynamic values when searching jsonb array of objects?

I am currently trying to build a query for finding specfic object within a jsonb array. I have the following query which works fine if I used a hard coded string for the "game" value e.g.

  const findGameQuery = `
        select playing
        from users
        where username = $1
        and playing @> '[{"game": "new-pokemon-snap"}]'
    `

However, if I use a dynamic value like I currently do for username, I get invalid json syntax error. e.g.

const findGameQuery = `
        select playing
        from users
        where username = $1
        and playing @> '[{"game": $2}]'
    `

    const { rows } = await query(findGameQuery, [username, game]);
    ctx.body = rows

How do I search using a dynamic value here? I have done a ton of searching and can't find any examples. $2 value is just a string so not sure why not accepted.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

When you send this query, it only has ONE parameter:

select playing
from users
where username = $1
and playing @> '[{"game": $2}]'

The correct query is:

select playing
from users
where username = $1
and playing @> $2

You have to make the array with the object in the parameter.

const gameObj = [{
    "game": game
}];
const gameParam = JSON.stringify(gameObj);
const { rows } = await query(findGameQuery, [username, gameParam]);
about 4 years ago · Juan Pablo Isaza Denunciar

0

You cannot use parameters in a string literal.

Construct the jsonb object with PostgreSQL functions:

const findGameQuery = `
      select playing
      from users
      where username = $1
      and playing @> jsonb_build_array(jsonb_build_object('game', $2))
  `
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda