[英]Import nested child of JSON file to Postgresql
我正在尝试从 JSON 文件中导入少量数据。 JSON 文件是嵌套的,我想导入子值。 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
]
}
}
]
}
]
}
我想获取以下子值(就像我用 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
列id
、 fid
、 name
、 longitude
、 latitude
我想出了一个解决方案,但只通过psql
插入父值,如type
、 properties
、 features
等
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 文件中获取所需的字段并将其插入到表的目标列中?
尝试这个
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
一种方法是使用jq提取 TSV 格式的数据(例如),然后将其导入数据库。
相关的 jq 过滤器与您的首选格式非常相似:
features[0].features[]
| [.id, .properties.fid, .properties.name, .geometry.coordinates[:2][] ]
| @tsv
由于您的 postgres 脚本无论如何都是从文件中读取的,因此在命令行中执行转换可能是最简单的,如下所示:
jq -f totsv.jq E:\myJson.json > myExtract.tsv
其中 totsv.jq 保存上面的 jq 脚本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.