【问题标题】:create an object from an existing json file using 'jq'使用“jq”从现有 json 文件创建对象
【发布时间】:2017-12-26 20:39:42
【问题描述】:

我有一个 messages.json 文件

[
    {
        "id": "title",
        "description": "This is the Title",
        "defaultMessage": "title",
        "filepath": "src/title.js"
      },
      {
        "id": "title1",
        "description": "This is the Title1",
        "defaultMessage": "title1",
        "filepath": "src/title1.js"
      },
      {
        "id": "title2",
        "description": "This is the Title2",
        "defaultMessage": "title2",
        "filepath": "src/title2.js"
      },
      {
        "id": "title2",
        "description": "This is the Title2",
        "defaultMessage": "title2",
        "filepath": "src/title2.js"
      },
    ]

我想创建一个对象

{
    "title": "Dummy1",
    "title1": "Dummy2",
    "title2": "Dummy3",
    "title3": "Dummy4"
  }

从顶部开始。 到目前为止我有

jq '.[] | .id' src/messages.json;

它确实给了我 ID 如何添加一些随机文本并像上面一样制作新对象?

我们也可以创建一个新的 JSON 文件并使用 jq 将新创建的对象写入它吗?

【问题讨论】:

    标签: json object jq


    【解决方案1】:

    您的输出包含“title3”,所以我假设您打算输入中第二次出现的“title2”应该是指“title3”。

    有了这个假设,下面的 jq 程序似乎可以做你想做的事:

    map( .id )
    | . as $in
    | reduce range(0;length) as $i ({};
        . + {($in[$i]): "dummy\(1+$i)"})
    

    换句话说,提取 .id 的值,然后将每个值转换为以下形式的对象:{(.id) : "dummy\(1+$i)"}

    这使用字符串插值,并产生:

    {
      "title": "dummy1",
      "title1": "dummy2",
      "title2": "dummy3",
      "title3": "dummy4"
    }
    

    无还原解决方案

    map(.id )
    | [., [range(0;length)]]
    | transpose
    | map( {(.[0]): "dummy\(.[1]+1)"})
    | add
    

    输出

    我们也可以创建一个新的json文件并使用jq将新创建的对象写入它吗?

    是的,只需使用输出重定向:

    jq -f program.jq messages.json > output.json
    

    附录

    我想要一个父对象“de”到已经创建的 json 文件对象

    您可以将上述任一解决方案发送至:{de: .}

    【讨论】:

    • “.title”、“.create”、“.edit”和“.delete”从何而来?也许您应该创建一个新的 SO 问题,因为原始问题和新问题之间似乎没有任何联系。
    • 修复了名称...这非常有效。谢谢。我对此略有增强,并希望结果 json 为“de”:{“title”:“dummy1”,“title1”:“dummy2”,“title2”:“dummy3”,“title3”:“dummy4”} .我尝试将 program.jq 编辑为 .地图(.id) | [., [范围(0;长度)]] |转置 |地图(“de”:{(.[0]):“虚拟(.[1]+1)”})|添加,但它给了我错误。基本上我想要一个父对象“de”到已经创建的 json 文件对象
    • 地图(.id)| [., [范围(0;长度)]] |转置 | {de: .} |地图({(.[0]):“虚拟(.[1]+1)”})|添加 。不工作
    • 这并不奇怪。见附录。
    • 你能用管道输入 {de: .} 来编写整个解决方案吗
    猜你喜欢
    • 2018-01-10
    • 1970-01-01
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多