jq update json-键是某些键的值,而值是某些其他键的值 [英] jq update json - key being value of some key and value being value of some other key

查看:72
本文介绍了jq update json-键是某些键的值,而值是某些其他键的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

样本 input.json


    [{
    "organizationId": "org1",
    "runtimeVersion": "3545",
    "type": "rest-api",
    "server": "test1",
    "status": "UP"
   }]

预期 output.json


      [{
    "organizationId": "org1",
    "runtimeVersion": "3545",
    "type": "rest-api",
    "server": "test1",
    "status": "UP",
    "test1": "UP"
  }]

输入是一个数组对象.我需要添加新密钥,它是密钥 server 的值.此新密钥的值应为密钥状态的值.

The input is an array object. I need to add new key which is the value of key server. The value of this new key should value of the key status.

任何使用 jq

推荐答案

本着Polya的如何解决"的精神,让我们首先观察一下要更新的对象位于数组中这一事实,这会分散注意力,因此,让我们专注于手头的任务:

In the spirit of Polya's "How to Solve It", let's start by observing that the fact that the object to be updated is in an array is a distraction, so let's focus on the task at hand:

将键值对添加到JSON对象

adding a key-value pair to a JSON object

因此,请记住添加"这个有用的词,实际上在查看jq手册时,您会同时找到"+"和"add".如果 .是起始对象,那么我们可以通过编写以下内容来实现更新:

"Add" is thus a helpful word to keep in mind, and indeed looking at the jq manual, you will find both "+" and "add". If . is the starting object, then we could achieve the update by writing:

. + {(.server): .status}

(由于必须计算.server,因此必须在.server周围加上括号.) 上面的表达式是一个过滤器,将过滤器应用于数组的每个成员的通常方法是使用map.这可能是解决该问题的最基本"方法(如我亲爱的沃森"):

(The parentheses around .server are necessary as .server has to be evaluated.) The above expression is a filter, and the usual way of applying a filter to each member of an array is using map. This leads to what might be the most "elementary" (as in "my dear Watson") solution to the problem:

map(. + {(.server): .status})

另一种方法是使用赋值语法"添加(或修改)密钥,从而得出更短的解决方案:

Another approach would be to use the "assignment syntax" to add (or modify) a key, leading to an even shorter solution:

map( .[.server] = .status )

也许这同样是基础...

Maybe that is no less elementary ...

这篇关于jq update json-键是某些键的值,而值是某些其他键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆