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

168
Vistas
Selectively pluck keys and values based on array from JSONB column

I'm looking for a way to pluck values from a JSONB object using an array of keys. Here's my JSON:

{
  "Foo1": 1,
  "Foo2": 2,
  "Foo3": 3,
  "Foo3": 4
}

I have a variable called "@Fields" which is of type TEXT[]. The array contains the name of the keys I'd like to pluck from the object ie. {'Foo1', 'Foo2'}. The result should be:

{
  "Foo1": 1,
  "Foo2": 2
}

I was using JSONB_EXTRACT_PATH("Data"::jsonb, "@Fields") however it seems the function requires passing in the paths as individual parameters whereas I want to give it an array somehow. Here's how it looks in my query:

SELECT
  "UserID",
  (
    CASE
      WHEN ARRAY_LENGTH("@Fields", 1) = 0 THEN "Data"
      ELSE JSONB_EXTRACT_PATH("Data", "@Fields")
    END
  ) AS "Data"
FROM
    UserMeta

I suspect I'll have to use JSON_EACH or something similar?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You can only remove keys one-by-one with the - operator. For everything else, you'll need a sub-select, where you extract each key-value pair, filter them (here comes your logic; which can be anything BTW), then aggregate the values together:

(select jsonb_object_agg(key, value)
 from   jsonb_each(data)
 where  key = any(keys_should_stay)) sub_select

Example use in context: http://rextester.com/OANQ93761

EDIT: If you want specific meaning to an empty array (i.e. retain all of the keys), use this predicate instead:

where  key = any(keys_should_stay)
or     cardinality(keys_should_stay) = 0
over 4 years ago · Santiago Trujillo 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