繁体   English   中英

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

[英]jq: how to add an object, key/value in a nested json tree with arrays

我对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"

在question []项目中获得类似以下内容:

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

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

从其他来源( 用jq在JSON结构中更深地转换键的名称 ),例如,我可以使用以下方式重命名键:

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))'

解决方案不必与我的尝试相符。 实际上,如果有更直接的完整方法,将不胜感激。

有什么问题:

.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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM