首页 > 解决方案 > 使用 jq 将数组转换为字符串

问题描述

我有一个 JSON 格式的原因数组[]["a","b","c"]. 基本上我想将 drop_reasons=["a","b","c"]json 替换为drop_reasons="a,b,c". 我知道我们可以将join(",")它与 jq 一起使用。但是,不知道如何在 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"}

标签: arraysjsonstringbashjq

解决方案


使用带有相关键的精简示例 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由于优先规则,它们是必需的。


推荐阅读