我需要帮助,因为我想从特定sid的json中解析python中的字段num1,num2和action。这是JSON代码。请帮忙,因为我是新手。
{
"contestants": [{
"sid": "53d88ec46fb1721307f3a185",
"u": {
"_id": {
"$id": "53d88ec46fb1721307f3a185"
},
"g": "M",
"id": "536lleepkyhnowfh67elpucsq",
"n": "Asif Khairani",
"st": "asif-khairani-53d88ec4b24d8"
},
"cl": {
"_id": {
"$id": "51ff5d1370b17224520002dc"
},
"st": "tirpude-institute-of-management-education",
"ti": "Tirpude Institute of Management Education",
"n": "Brands",
"cst": "brands",
"r": null,
"c": null
},
"ct": "nagpur",
"tv": 124,
"cf": 20,
"picture": "http:\/\/images.iimg.in\/u\/53d88ec46fb1721307f3a185-190-190\/asif-khairani-53d88ec4b24d8.img",
"action": "+",
"voteText": "Votes",
"num1": 6,
"num2": 5
}]
}
答案 0 :(得分:1)
使用json模块;
import json
myFile = open(youtJsonFile, 'r')
yourJsonText = myFile.read()
myFile.close()
myObject = json.loads(yourJsonText)
# Access your Json file by dict or lists python
print myObject['contestants'][0]['num1']
print myObject['contestants'][0]['num2']
答案 1 :(得分:0)
首先,您需要在脚本/代码中import json
,然后将所有JSON代码放在单引号之间,以使您的JSON成为字符串:
raw_json = '{"contestants":[{"sid":"53d88ec46fb1721307f3a185","u":{"_id":{"$id":"53d88ec46fb1721307f3a185"},"g":"M","id":"536lleepkyhnowfh67elpucsq", "n":"Asif Khairani","st":"asif-khairani-53d88ec4b24d8"},"cl":{"_id":{"$id":"51ff5d1370b17224520002dc"},"st":"tirpude-institute-of-management-education","ti":"Tirpude Institute of Management Education","n":"Brands","cst":"brands","r":null,"c":null},"ct":"nagpur","tv":124,"cf":20,"picture":"http:\/\/images.iimg.in\/u\/53d88ec46fb1721307f3a185-190-190\/asif-khairani-53d88ec4b24d8.img","action":"+","voteText":"Votes","num1":6,"num2":5}]}'
一旦你在变量raw_json
中拥有JSON代码就像一个字符串,你必须这样做:
parsed_json = json.loads(raw_json)
并且您将拥有类似python dict的JSON代码,并且可以访问以下字段:
parsed_json['contestants'] # Get contenstants list
parsed_json['contestants'][0] # Get first object in contestants list
或任何你需要的东西!