2017-03-31 2 views
2

저는 JQ에 매우 익숙합니다. ... 분명히 보이는 경우 미안합니다 ... 맨 처음 문제가 있습니다.jq : 배열을 사용하여 중첩 된 json 트리에 객체, 키/값을 추가하는 방법

링크 : https://github.com/mariotti/technical_interview_questions/blob/master/QUESTIONS.json

추출 나는이 JSON 파일이 있습니다. 얻을 수있는 질문 [] 항목에서

"codefile" : "a string to be defined" 

: 나는 키/필드를 추가 할

{ 
"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" 
     }, 

: 당신이 볼 수 있듯이

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 
} 

,이에 "깊이"입니다 다음과 같이 입력하십시오 :

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

그리고 저는 그것을하고 싶습니다. 내가 성공하지 않고이 비트를 수정하려고했다

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

: 캘리 내가 예를 들어이와 키의 이름을 바꿀 수 ... 조금 더 개발하기 위해 다른 소스 (Transforming the name of key deeper in the JSON structure with jq)에서

을해야 할 수도있다. 단순히 키/값을 추가 할 수없는 것 같습니다!

이상한 참조와 추가 시도 목록으로 인해 과부하가 걸리지 않도록하십시오.

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

이 솔루션은 내 시도 일치하지 않습니다 하지만 어쩌면 내가 당신에게 시도의 예를 제공합니다. 사실 더 직선적 인 전체 방법이 있다면 매우 감사하게 생각합니다.

답변

2

뭐가 잘못 :

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

감사합니다 많이! 둘 다 잘 작동합니다. 아마도 첫 번째 라인에서, 나는 걷기/뽑기를 시도하는 것에 갇혀있었습니다 ... 실제로 두 번째 비트입니다. 실제로 나는 "with_entries"에 갇혀있었습니다. 완전한! 어쨌든 우스운 행동을보고하고 싶습니다. 파일의 필터 만 사용하면 키의 순서가 유지되지 않습니다. 재미있는 점은 일관성이없는 것 같습니다. – mariotti

+0

다른 사람들을 돕기 위해이 질문에 답하십시오. 나에게 그것은 'TechQuestions.category []. question [] '이 필터 일뿐만 아니라 조작의 RHS라는 것을 이해하기가 어렵다. – mariotti

+0

@mariotti - "LHS"라고 쓰고 싶다고 생각합니다. 키 순서 변경은 잠재적으로 불편하지만 의미 상으로는 문제가되지 않습니다. 그러나 -S 명령 행 옵션을 고려할 수도 있습니다. – peak