在Postgres中解析JSON

时间:2018-02-19 14:52:00

标签: json parsing postgresql-9.6

我有以下JSON,我想在postgresql函数中解析。

    {
      "people": [
        {
          "person_name": "Person#1",
          "jobs": [
            {
              "job_title": "Job#1"
            },
            {
              "job_name": "Job#2"
            }
          ]
        }
      ]
    }

我需要知道如何取出person_name,然后循环通过作业并拉出job_title。这是我能够得到的。

select ('{"people":[{"person_name":"Person#1","jobs":[{"job_title":"Job#1"},
{"job_name":"Job#2"}]}]}')::json -> 'people';

1 个答案:

答案 0 :(得分:0)

https://www.db-fiddle.com/f/vcgya7WtVdvj8q5ck5TqgX/0

假设您帖子中的job_name应该是job_title。我将您的测试数据扩展到:

{
    "people": [{
        "person_name": "Person#1",
        "jobs": [{
            "job_title": "Job#11"
        },
        {
            "job_title": "Job#12"
        }]
    },
    {
        "person_name": "Person#2",
        "jobs": [{
            "job_title": "Job#21"
        },
        {
            "job_title": "Job#22"
        },
        {
            "job_title": "Job#23"
        }]
    }]
}

查询:

SELECT 
    person -> 'person_name' as person_name,                            -- B
    json_array_elements(person -> 'jobs') -> 'job_title' as job_title  -- C
FROM (
    SELECT 
        json_array_elements(json_data -> 'people') as person           -- A
    FROM (
        SELECT (
            '{"people":[ '
            ||     '{"person_name":"Person#1","jobs":[{"job_title":"Job#11"}, {"job_title":"Job#12"}]}, ' 
            ||     '{"person_name":"Person#2","jobs":[{"job_title":"Job#21"}, {"job_title":"Job#22"}, {"job_title":"Job#23"}]} '
            || ']}'
        )::json as json_data
    )s
)s

获取人数组; json_array_elements将所有数组元素扩展为每个元素一行

B从数组元素中获取person_name

C将作业数组元素扩展为每个元素一行并获得job_title

结果:

person_name  job_title  
-----------  ---------  
"Person#1"   "Job#11"   
"Person#1"   "Job#12"   
"Person#2"   "Job#21"   
"Person#2"   "Job#22"   
"Person#2"   "Job#23"