问题
I have the following geojson file:
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {
"LINE": "RED",
"STATION": "Harvard"
},
"geometry": {
"type": "Point",
"coordinates": [-71.118906072378209, 42.37402923068516]
}
},
{
"type": "Feature",
"properties": {
"LINE": "RED",
"STATION": "Ashmont"
},
"geometry": {
"type": "Point",
"coordinates": [-71.063430144389983, 42.283883546225319]
}
}
]
}
I would like to append the second object within the "features" array to the end of it, creating 3 total objects. Using the below snippet errors out with "array ([{"type":"F...) and object ({"type":"Fe...) cannot be added". Is there a way to do this using jq without hardcoding the key:value pairs as seen here?
cat red_line_nodes.json | jq '.features |= . + .[length-1]' > red_line_nodes_2.json
回答1:
Short jq
solution:
jq '.features |= . + [.[-1]]' red_line_nodes.json
The output:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"LINE": "RED",
"STATION": "Harvard"
},
"geometry": {
"type": "Point",
"coordinates": [
-71.11890607237821,
42.37402923068516
]
}
},
{
"type": "Feature",
"properties": {
"LINE": "RED",
"STATION": "Ashmont"
},
"geometry": {
"type": "Point",
"coordinates": [
-71.06343014438998,
42.28388354622532
]
}
},
{
"type": "Feature",
"properties": {
"LINE": "RED",
"STATION": "Ashmont"
},
"geometry": {
"type": "Point",
"coordinates": [
-71.06343014438998,
42.28388354622532
]
}
}
]
}
回答2:
For reference, an alternative to using |= . + ...
is to use +=
. In your case, however, you would have to write:
.features += [.features[-1]]
so it's no shorter.
来源:https://stackoverflow.com/questions/48983196/how-can-i-duplicate-an-existing-object-within-a-json-array-using-jq