【问题标题】:Sed - Remove an array element from JSON stringSed - 从 JSON 字符串中删除一个数组元素
【发布时间】:2021-10-15 15:33:11
【问题描述】:

我有一个 JSON 字符串作为单行文件,元素之间没有空格。这就是 JSON 的样子。

{"data":[{"ids":[{"index":"01","type":"02","id":"XYZ12345"}],"scores":[{"name":"STKOVERFLOW","cardName":"08","cardVersion":"10","date":"10062019","score":"00730","reasons":[{"code":"X2345","value":"01"}]}],"telephones":[{"index":"01","number":"9841234567","extension":"4424386","type":"01"}]}]}

我必须从 JSON 树中删除分数数组。

我的想法是先删除reasons数组,然后删除scores数组

我尝试了几种方法,但它不起作用。任何帮助表示赞赏。

 sed 's/\,\"reasons.*\]//' < input.json      #This removes "]" till the last array present in the json.

sed 's/\,\"reasons.*?\]//' < input.json      #This does not remove any characters in the input

sed 's/\,\"reasons(.*?)\]//' < input.json    #This does not remove any characters in the input

我想使用 sed 来实现这一点,因为组织中现在没有其他工具。

感谢您的帮助。谢谢!!

【问题讨论】:

    标签: regex linux sed


    【解决方案1】:

    使用jq 在脚本(或其他理解数据格式的工具)中操作 JSON,而不是 sed 或其他任何依赖正则表达式的东西。

    jq -c 'del(.data[0].scores)' input.json > output.json
    

    【讨论】:

    • 感谢您的回答!! jq 在系统中不可用,安装 jq 是一个繁琐的过程。使用 sed 实现此目的的任何建议
    • @Parthiban 完成繁琐的过程。试图使用一个不懂 JSON 的工具来操作 JSON 就像是用螺丝刀切割一张胶合板。这份工作完全错了。
    • perl 或 python 脚本是另一种选择;两者都在其标准库中附带 JSON 解析器。
    • 可以添加python脚本来实现吗?
    猜你喜欢
    • 2020-05-29
    • 2023-03-04
    • 1970-01-01
    • 2017-02-09
    • 2015-06-23
    • 1970-01-01
    • 2020-05-18
    • 2020-08-29
    • 1970-01-01
    相关资源
    最近更新 更多