gpt4 book ai didi

json - 使用 JQ 将 Geojson 附加到 json 字段

转载 作者:行者123 更新时间:2023-12-04 08:43:02 25 4
gpt4 key购买 nike

我有一个我正在处理的项目,它创建了一个等值线 map ,其中包含从 file1.json 加载的所有美国县边界。并根据 file2.json 中的值填充颜色渐变.在之前的迭代中,我只是将值手动输入到 file1.json 中。 ,但现在我想扩展我的 map 并使其更加用户友好。file1.json结构如下:

{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"GEO_ID": "0500000US06001",
"STATE": "06",
"COUNTY": "001",
"NAME": "Alameda",
"LSAD": "County",
"CENSUSAREA": 739.017
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
-122.30936,
37.77615
],
[
-122.317215,
37.778527
]
]
]
}
},
...
]
}
file2.json结构如下:
[
{
"County": "Alameda",
"Count": 25
},
{
"County": "Amador",
"Count": 1
},
{
"County": "Butte",
"Count": 2
},
...
]
我想创建一个包含来自 file1.json 的所有内容的新文件,但附加它以包含基于 County 字段的相关 Count 字段。
结果如下所示:
[
{
"type": "Feature",
"properties": {
"GEO_ID": "0500000US06001",
"STATE": "06",
"COUNTY": "001",
"NAME": "Alameda",
"Count": "25",
"LSAD": "County",
"CENSUSAREA": 739.017
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
-122.30936,
37.77615
],
[
-122.317215,
37.778527
]
]
]
}
},
...
]
我刚开始使用 jq ,但我已经玩够了让它在 PowerShell 中运行。

最佳答案

这是一个 test.jq可能有帮助的文件

# utility to create lookup table from array of objects
# k is the name to use as the key
# f is a function to compute the value
#
def obj(k;f): reduce .[] as $o ({}; .[$o[k]] = ($o | f));

# create map from county to count
( $file2 | obj("County";.Count) ) as $count

# add .properties.Count to each feature
| .features |= map( .properties.Count = $count[.properties.NAME] )
假设适用的示例使用 file1.jsonfile2.json :
$ jq -M --argfile file2 file2.json -f test.jq file1.json
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"GEO_ID": "0500000US06001",
"STATE": "06",
"COUNTY": "001",
"NAME": "Alameda",
"LSAD": "County",
"CENSUSAREA": 739.017,
"Count": 25
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
-122.30936,
37.77615
],
[
-122.317215,
37.778527
]
]
]
}
}
]
}
Try it online!
我注意到“Count”在您的示例输出中是一个字符串,但它在示例文件 2 中是一个数字。如果您需要将其转换为字符串,您可以调用 tostring .例如
.features |= map( .properties.Count = ( $count[.properties.NAME] | tostring ) )
或者您可以在创建查找表时执行转换,例如
  ( $file2 | obj("County"; .Count | tostring ) ) as $count

关于json - 使用 JQ 将 Geojson 附加到 json 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64469597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com