简体   繁体   中英

extract specific returning field in json using postgres

I have the following JSON :

{ "firstName": "John",
  "lastName": "Smith",
  "isAlive": true,
  "age": 27,
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": "10021-3100"
  },
  "phoneNumbers": [
    {
      "type": "home",
      "number": "212 555-1234"
    },
    {
      "type": "office",
      "number": "646 555-4567"
    },
    {
      "type": "mobile",
      "number": "123 456-7890"
    }
  ],
  "children": [],
  "spouse": "Maria"
}

and I am trying to get an array or a table of all the numbers the user have, some users have only 1 number and some have many, is there a way to call all "number" within the json

I am going to try to answer this on my phone, so please forgive the brevity.

SELECT user->>'firstName' as first_name
  , user->>'lastName' as last_name
  , phone_type
  , phone_number
FROM users_tbl
CROSS JOIN LATERAL jsonb_array_elements(user->'phoneNumbers') jarr(num_obj)
CROSS JOIN LATERAL (
  SELECT num_obj->>'type' AS phone_type
    , num_obj->>'number' AS phone_number
  ) nums

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM