将JSON文件的嵌套子级导入Postgresql
我试图从JSON文件中导入一些数据。JSON文件是嵌套的,我想导入子值。JSO结构是这样的将JSON文件的嵌套子级导入Postgresql,json,postgresql,psql,jq,Json,Postgresql,Psql,Jq,我试图从JSON文件中导入一些数据。JSON文件是嵌套的,我想导入子值。JSO结构是这样的 { "type": "FeatureCollection", "properties": { "zoom": 14, "x": 12302, "y": 7075 }, "features": [ { "type": "FeatureCollection", "pr
{
"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调用它一样)
进入myTable
标题列id
,fid
,名称
,经度
,纬度
我提出了一个解决方案,但它只插入父值,如type
,properties
,features
,通过psql
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;
其中,功能
作为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
一种方法是使用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脚本
jq -f totsv.jq E:\myJson.json > myExtract.tsv