Search code examples
jsonpostgresqlobject

Get nested objects values from JSON in Postgres


So here is my JSON column in my Postgres DB:

{
  "objekt_art": {
    "86": {
      "code": "86",
      "bezeichnung_de": "Kino",
      "bezeichnung_fr": "Cinéma",       
      "bezeichnung_it": "Cinema",
      "bezeichnung_en": null,
      "kurz_bezeichnung_de": "Kino",
      "relevant_fuer_berechnung_steuerquote": true
    },
    "27": {
      "code": "27",
      "bezeichnung_de": "Kiosk",
      "bezeichnung_fr": "Kiosque",
      "bezeichnung_it": "Chiosco",
      "bezeichnung_en": null,
      "kurz_bezeichnung_de": "Kiosk",
      "relevant_fuer_berechnung_steuerquote": true
    }
  }
}

I need to be able to query the bezechnung_de for example where code = 86. The number of code i can pass from another table.

How can i for example make a query with two columns. One with the number and the second with bezeichnung_de.

Like this:

Code Bez
86   Kino

Solution

  • Sample data structure and sample table for join data: dbfiddle

    select
      je.value -> 'code' as "Code",
      je.value -> 'bezeichnung_de' as "Bez"
    from
      test t
      cross join jsonb_each((data::jsonb ->> 'objekt_art')::jsonb) je
      -- In table test_join I insert value 86 for join record
      inner join test_join tj on je.key::int = tj.json_id