实际上,密钥必须在JSON对象中是唯一的(例如Does JSON syntax allow duplicate keys in an object?)。但是,假设我有一个包含以下内容的文件:
{
"a" : "1",
"b" : "2",
"a" : "3"
}
是否有将重复键转换为数组的简单方法?这样文件就变成了:
{
"a" : [ {"key": "1"}, {"key": "3"}],
"b" : "2"
}
或类似的东西,但它将重复的键组合成一个数组(或查找和替代方法来提取重复的键值)。
以下是Java的解决方案:Convert JSON object with duplicate keys to JSON array
有没有办法用awk / bash / python做到这一点?
答案 0 :(得分:5)
如果您的输入实际上是一个平面JSON对象,其基元为值,则应该可以:
jq -s --stream 'group_by(.[0]) | map({"key": .[0][0][0], "value": map(.[1])}) | from_entries'
{
"a": [
"1",
"3"
],
"b": [
"2"
]
}
对于更复杂的输出,这需要实际了解--stream
应该如何使用,这超出了我的范围。
答案 1 :(得分:2)
使用-s --stream
建立圣地亚哥的答案,以下过滤器一次一步地构建对象,从而保留键的顺序和特定键的值:
reduce (.[] | select(length==2)) as $kv ({};
$kv[0][0] as $k
|$kv[1] as $v
| (.[$k]|type) as $t
| if $t == "null" then .[$k] = $v
elif $t == "array" then .[$k] += [$v]
else .[$k] = [ .[$k], $v ]
end)
对于给定的输入,结果是:
{
"a": [
"1",
"3"
],
"b": "2"
}
为了说明保留每个键的值的顺序,请考虑以下输入:
{
"c" : "C",
"a" : "1",
"b" : "2",
"a" : "3",
"b" : "1"
}
上述过滤器产生的输出是:
{
"c": "C",
"a": [
"1",
"3"
],
"b": [
"2",
"1"
]
}
答案 2 :(得分:0)
在峰值答案的基础上,以下过滤器适用于多个对象输入,适用于嵌套对象,适用于无法使用slurp-Option ( -s )。
这不是最初问题的答案,但因为这里的jq-FAQ链接可能对某些访问者有用
文件 jqmergekeys.txt
def consumestream($arr): # Reads stream elements from stdin until we have enough elements to build one object and returns them as array
input as $inp
| if $inp|has(1) then consumestream($arr+[$inp]) # input=keyvalue pair => Add to array and consume more
elif ($inp[0]|has(1)) then consumestream($arr) # input=closing subkey => Skip and consume more
else $arr end; # input=closing root object => return array
def convert2obj($stream): # Converts an object in stream notation into an object, and merges the values of duplicate keys into arrays
reduce ($stream[]) as $kv ({}; # This function is based on http://stackoverflow.com/a/36974355/2606757
$kv[0] as $k
| $kv[1] as $v
| (getpath($k)|type) as $t # type of existing value under the given key
| if $t == "null" then setpath($k;$v) # value not existing => set value
elif $t == "array" then setpath($k; getpath($k) + [$v] ) # value is already an array => add value to array
else setpath($k; [getpath($k), $v ]) # single value => put existing and new value into an array
end);
def mainloop(f): (convert2obj(consumestream([input]))|f),mainloop(f); # Consumes streams forever, converts them into an object and applies the user provided filter
def mergeduplicates(f): try mainloop(f) catch if .=="break" then empty else error end; # Catches the "break" thrown by jq if there's no more input
#---------------- User code below --------------------------
mergeduplicates(.) # merge duplicate keys in input, without any additional filters
#mergeduplicates(select(.layers)|.layers.frame) # merge duplicate keys in input and apply some filter afterwards
示例:
tshark -T ek | jq -nc --stream -f ./jqmergekeys.txt
答案 3 :(得分:0)
这是一个可以很好地概括的简单选择:
def augmentpath($path; $value):
getpath($path) as $v
| setpath($path; $v + [$value]);
reduce (inputs | select(length==2)) as $pv
({}; augmentpath($pv[0]; $pv[1]) )
jq -n -f reshape.jq input.json
使用给定的输入:
{
"a": [
"1",
"3"
],
"b": [
"2"
]
}
如果避免单例数组很重要,则可以修改augmentpath
的def或添加后处理步骤。