Search code examples
postgresqlpostgresql-13

How to query jarray in jsonb field type?


I have a jsonb field type in a table, it contains the JArray:

[
  {
    "code": "F01",
    "name": "Apple"
  },
  {
    "code": "F02",
    "name": "Orange"
  },
  {
    "code": "F03",
    "name": "Banana"
  }
]

I try to query based on the code and expecting the name like below:

select a.myarray name from fruits a where a.myarray ->> 'code' = 'F02'

but it returns empty

What I missed?


Solution

  • select j ->> 'name' 
    from jsonb_array_elements(
    '[
      {"code": "F01","name": "Apple"},
      {"code": "F02","name": "Orange"},
      {"code": "F03","name": "Banana"}
    ]'::jsonb) j
    where j ->> 'code' = 'F02';
    

    Replace the literal JSON text with the actual value.