jq:如何在带有数组的嵌套json树中添加对象,键/值

时间:2017-03-31 20:01:41

标签: json jq

我对JQ很新...很抱歉,如果它看起来很明显.. 首先是裸问题。我有这个JSON文件:

链接:https://github.com/mariotti/technical_interview_questions/blob/master/QUESTIONS.json

提取。

cat QUESTIONS.json | jq '.TechQuestions.category[0,1].question[0,1]'
output:
{
ID: Q1,
categoryname: General,
idC: C1,
idCQ: C1Q1,
idQ: Q1,
title: Find the most frequent integer in an array
}
{
ID: Q21,
categoryname: Strings,
idC: C2,
idCQ: C2Q1,
idQ: Q1,
title: Find the first non-repeated character in a String
}
{
ID: Q2,
categoryname: General,
idC: C1,
idCQ: C1Q2,
idQ: Q2,
title: Find pairs in an integer array whose sum is equal to 10 (bonus; do it in linear time)
}
{
ID: Q22,
categoryname: Strings,
idC: C2,
idCQ: C2Q2,
idQ: Q2,
title: Reverse a String iteratively and recursively
}

正如您所看到的,这是“深入”:

{
"TechQuestions": {
"category": [
  {
    "catname": "General",
    "idC": "C1",
    "question": [
      {
        "ID": "Q1",
        "categoryname": "General",
        "idC": "C1",
        "idCQ": "C1Q1",
        "idQ": "Q1",
        "title": "Find the most frequent integer in an array"
      },

我想添加键/字段:

"codefile" : "a string to be defined"

在问题[]项目中得到类似的东西:

      {
        "ID": "Q1",
        "categoryname": "General",
        "idC": "C1",
        "idCQ": "C1Q1",
        "idQ": "Q1",
        "title": "Find the most frequent integer in an array",
        "codefile" : "not present"
      },

我想以编程方式进行,因为我可能需要进一步开发......

从其他来源(Transforming the name of key deeper in the JSON structure with jq)我可以用例如:

重命名一个键
cat QUESTIONS.json | jq '.' | jq '
# Apply f to composite entities recursively, and to atoms
def walk(f):
 . as $in
 | if type == "object" then
      reduce keys[] as $key
        ( {}; . + { ($key):  ($in[$key] | walk(f)) } ) | f
  elif type == "array" then map( walk(f) ) | f
  else f
  end;
(.  |= walk(
           if type == "object"
           then with_entries( if .key == "name" then .key |= sub("name";"title") else . end)
           else .
           end))'

我试图修改这一点但没有成功。看来我无法简单地添加键/值!

我将避免使用奇数引用和进一步的尝试列表来重载您。 但也许我给你一个尝试的例子:

(.  |= walk(
       if type == "object"
       then with_entries(
            if .key == "question"
            then . = ( . + {"freshly": "added"})
            else .
            end)
       else .
       end))'

解决方案不一定与我的尝试相符。实际上,如果有一个更直接的完整方式,非常感谢。

1 个答案:

答案 0 :(得分:4)

错误:

.TechQuestions.category[0,1].question[] += {"codefile" : "a string to be defined"}

使用walk/1,您可以考虑:

walk( if type == "object" and has("question")
      then .question[] += {"codefile" : "a string to be defined"}
      else .
      end)