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

telwanggs 阅读:20 2025-01-19 22:14:33 评论:0

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

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

从其他来源( 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))' 

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

请您参考如下方法:

有什么问题:

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


标签:json
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号