将嵌套的 child 个 JSON 个文件导入 Postgresql

Import nested child of JSON file to Postgresql

我正在尝试从 JSON 文件中导入少量数据。 JSON 文件是嵌套的,我想导入 child 值。 JSO 结构是这样的

{
    "type": "FeatureCollection",
    "properties": {
        "zoom": 14,
        "x": 12302,
        "y": 7075
    },
    "features": [
        {
            "type": "FeatureCollection",
            "properties": {
                "layer": "poi",
                "version": 3,
                "extent": 4096
            },
            "features": [
                {
                    "type": "Feature",
                    "id": 4356,
                    "properties": {
                        "fid": "eg-34678h765",
                        "name": "Brooklyn Children's Museum"
                    },
                    "geometry": {
                        "type": "Point",
                        "coordinates": [
                            -73.944030,
                            40.674427
                        ]
                    }
                }
            ]
        }
    ]
}

我想获取以下 child 值(就像我用 JS 调用它一样)

features[0].features[i].id
features[0].features[i].properties.fid
features[0].features[i].properties.name
features[0].features[i].geometry.coordinates[0]
features[0].features[i].geometry.coordinates[1]

进入 myTable 标题列 idfidnamelongitudelatitude

我想出了一个解决方案,但只能通过 psql[= 插入 typepropertiesfeatures 等 parent 值27=]

copy temp_json from 'E:\myJson.json';

insert into myTable ("type", "properties", "features") 

select values->>'type' as type,
       values->>'properties' as properties,
       values->>'features' as features
from   (
           select json_array_elements(replace(values,'\','\')::json) as values 
           from   temp_json
       ) a;

其中 features 插入为 JSONB

如何从 JSON 文件中获取我想要的字段并插入到我的 table 的目标列中?

试试这个

select j2->>'id' as id,
       j2->'properties'->>'fid'  as fid,
       j2->'properties'->>'name' as name,
       MAX( CASE WHEN l.k = 1 THEN l.cord end ) as longitude,
       MAX( CASE WHEN l.k = 2 THEN l.cord end ) as latitude
       from temp_json 
    cross join json_array_elements(values->'features') as j1
    cross join json_array_elements(j1->'features') as j2
    cross join json_array_elements_text(j2->'geometry'->'coordinates')
                                 with ordinality l(cord,k)
                                 GROUP BY 1,2,3

DEMO

一种方法是使用 提取 TSV 格式的数据(例如),然后将其导入数据库。

相关的 jq 过滤器与您的首选格式非常相似:

features[0].features[]
| [.id, .properties.fid, .properties.name, .geometry.coordinates[:2][] ]
| @tsv

因为你的 postgres 脚本无论如何都是从文件中读取的,所以它可能是最简单的 按照以下行在 command-line 处执行转换:

jq -f totsv.jq E:\myJson.json > myExtract.tsv

其中 totsv.jq 保存上面的 jq 脚本。