简体   繁体   English

使用 jq 或 Python 解析 JSON

[英]Parsing JSON using jq or Python

I have this nested JSON我有这个嵌套的 JSON

[
  "[[Input=[Name=ABC, createDateTime=2019-30-11, RollNumber=9]]]",
  "[[SubjectList=[Summer=, Winter=, Autumn=, Spring=, rList=, sList=, additionalList=, emailList=, FoodList=, sAssignmentList=, summerworkList=, outdoorList=, movielist=]]]",
  "[ProcessingDate=2018-10-06]",
  "[Hobbies=Football]",
  "[Phone=Android,,]"
]

How can I process this JSON and get the value football or rollnumber using Python?如何处理这个 JSON 并使用 Python 获得价值 football 或 rollnumber?

This is what I tried:这是我尝试过的:

Code代码

import json
row = '''[
  "[[Input=[Name=ABC, createDateTime=2019-30-11, RollNumber=9]]]",
  "[[SubjectList=[Summer=, Winter=, Autumn=, Spring=, rList=, sList=, additionalList=, emailList=, FoodList=, sAssignmentList=, summerworkList=, outdoorList=, movielist=]]]",
  "[ProcessingDate=2018-10-06]",
  "[Hobbies=Football]",
  "[Phone=Android,,]"
]'''
row_dict = json.loads(row)
print(row_dict[3])

Using this - I get following output:使用这个 - 我得到以下 output:

[Hobbies=Football] [爱好=足球]

But I am missing next level parsing to get just football as output但是我缺少下一级解析来获得足球,如 output

Here is an approach that uses capture on the non-json strings in the array.这是一种在数组中的非 json 字符串上使用capture的方法。
It assumes the [:alnum:] posix regex character class suffices to match the values after the =它假定[:alnum:] posix 正则表达式字符 class 足以匹配 = 之后的值
Sample execution assuming data in test.json假设test.json中的数据的示例执行

$ jq -M '.[] | capture("Hobbies=(?<Hobbies>[[:alnum:]]+)")' test.json
{
  "Hobbies": "Football"
}

Here is a variation which produces exactly Football :这是一个准确产生Football的变体:

$ jq -Mr '.[] | capture("Hobbies=(?<Hobbies>[[:alnum:]]+)") | .Hobbies' test.json
Football

Here's an example script which uses multiple captures and combines them with add这是一个示例脚本,它使用多个捕获并将它们与add相结合

[ .[]
  |  capture("Hobbies=(?<Hobbies>[[:alnum:]]+)")
   , capture("RollNumber=(?<RollNumber>[[:alnum:]]+)")
] | add

Sample execution assuming script in test.jq test.jq中假设脚本的示例执行

$ jq -M -f test.jq test.json
{
  "RollNumber": "9",
  "Hobbies": "Football"
}

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

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