【问题标题】:Transform array to string using jq使用 jq 将数组转换为字符串
【发布时间】:2020-10-29 17:16:07
【问题描述】:

我有一个带有原因数组的 json,格式为 []["a","b","c"]。基本上我想更换 drop_reasons=["a","b","c"] 在 json 到 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"}

【问题讨论】:

    标签: arrays json string bash jq


    【解决方案1】:

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

    【讨论】:

    • 添加了示例 json
    • 哇!这行得通,我知道'|='更新符号,但上次我使用它时,它用 1 个值更新了所有值,也许我当时用错了,无论如何谢谢!
    【解决方案2】:

    我不熟悉jq,但如果你只是将每个"," 替换为,,就可以了。这是一个 hack,因此如果输入数据更改格式,它可能会中断。

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

    【讨论】:

    • 这将更改 json 中的所有逗号
    • 如果它们被双引号包围,是的。根据样本数据,它会起作用。如果您有更完整的输入文件,您可以分享我可以做得更好。不过,它可能是一个 Python 脚本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 2016-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多