将引号添加到json数组并使用jq添加属性键

时间:2018-04-25 13:26:56

标签: json jq

以下是我原来的json:

{
"type": "type1",
"name": "abc",
"features": [
{ "type": "Feature", "properties": { "district": "d1", "district_code": "101", "block_code": "1010070" }},
{ "type": "Feature", "properties": { "district": "d1", "district_code": "101", "block_code": "1010100" }}]
}

我的预期结果:

[
  {
    "Data": "{\"properties\":{\"district\":\"d1\",\"district_code\":\"101\",\"block_code\":\"1010070\"}}"
   },
  {
    "Data": "{\"properties\":{\"district\":\"d1\",\"district_code\":\"101\",\"block_code\":\"1010100\"}}"
  }
]

到目前为止,我只能通过以下方式添加引号:

.features[] | del(.type) | tojson

只会给我:

"{\"properties\":{\"district\":\"d1\",\"district_code\":\"101\",\"block_code\":\"1010070\"}}"
"{\"properties\":{\"district\":\"d1\",\"district_code\":\"101\",\"block_code\":\"1010100\"}}"

提前致谢!

1 个答案:

答案 0 :(得分:2)

jq '.features | map(del(.type) | {Data: tojson})' file.json 方法:

[...]

或与数组构造jq '[.features[] | del(.type) | {Data: tojson}]' file.json 相同:

[
  {
    "Data": "{\"properties\":{\"district\":\"d1\",\"district_code\":\"101\",\"block_code\":\"1010070\"}}"
  },
  {
    "Data": "{\"properties\":{\"district\":\"d1\",\"district_code\":\"101\",\"block_code\":\"1010100\"}}"
  }
]

输出:

0