使用jq将数组转换为字符串

时间:2020-10-29 17:16:07

标签: arrays json string bash jq

我有一个json,其原因数组的格式为[]["a","b","c"]。基本上我想更换 json中的drop_reasons=["a","b","c"]drop_reasons="a,b,c"我知道我们可以在jq中使用join(","),但是,不知道如何在json中对其进行修改。

我已经尝试过- cat test.json | jq ' .drop_reasons = .drop_reasons | join(",") ' | sponge test.json ,但看不到起作用,它尝试加入整个json,而不仅仅是drop_reasons。我该如何解决?任何帮助将不胜感激。谢谢

示例json是:

{"id":11828997,"user":"8ddbceef-c374-44be-82f6-996b9d3f9cbd","timestamp":"2020-08-12T05:50:00+05:30","claim_timestamp":"2020-08-12T20:30:58+05:30","unique_key":"d56af2a7-10b8-4a98-b12c-a8aeab9fc56e","platform":"android","location_type":"indoor","activity_type":"unknown","activity_confidence":0,"total_day_steps":151744,"gf_total_steps":0,"step_count":122,"session_id":"1792b79c-1490-4b13-83e2-3c50ebce28f4","label":"indoor","is_claimed":false,"is_dropped":false,"drop_reasons":[],"is_valid":false,"invalid_reason":["steps>allowed_freq"],"conversion":null,"createdAt":"2020-08-12T20:30:58.385285+05:30","updatedAt":"2020-08-12T20:30:58.385285+05:30","location_uuid":null,"location_latitude":28.6673,"location_longitude":77.3915,"location_accuracy":1000,"location_speed":0,"location_timestamp":"2020-08-12T05:46:40+05:30","location_altitude":0,"location_ios_distance_filler":null,"location_ios_desired_accuracy":null,"location_distance_filter":0,"location_desired_accuracy":0,"location_course":0,"location_floor":null,"meta_data_geo_string":"28.6672867,77.3914746","meta_data_timezone":"Asia/Kolkata","meta_data_device_model":"Redmi Note 8 Pro","meta_data_device_brand":"redmi","meta_data_device_manufacturer":"xiaomi","meta_data_app_version":"0.9.31","meta_data_bundle_id":"com.pepkit.ssg","meta_data_build_no":"213","meta_data_plan_id":"a562ad72-54a9-4aea-941c-7f075e2a8b18"}

2 个答案:

答案 0 :(得分:2)

仅使用相关密钥使用简化的示例JSON对象:

$ cat test.json
{
    "drop_reasons": ["a","b","c"]
}
$ jq '.drop_reasons |= join(",")' test.json
{
  "drop_reasons": "a,b,c"
}

您的带有空数组的样本将更改为空字符串。


x |= y本质上是x = (x | y)的简写。企图是您尝试中所缺少的;由于jq优先规则,因此需要使用它们。

答案 1 :(得分:-2)

我对jq不熟悉,但是如果您仅用","替换每个,,它就可以解决问题。这是一种黑客行为,因此如果输入数据更改格式,它可能会中断。

$ cat temp.txt 
drop_reasons=["a","b","c"]

$ perl -pe 's/","/,/g' temp.txt
drop_reasons=["a,b,c"]