如何在 Python 中解析 JSON 并将 2 个字段放入字典中? [复制]
Posted
技术标签:
【中文标题】如何在 Python 中解析 JSON 并将 2 个字段放入字典中? [复制]【英文标题】:How to parse JSON and put 2 fields in dictionary in Python? [duplicate] 【发布时间】:2018-11-19 20:45:50 【问题描述】:我想解析 JSON 文件并从 JSON 中获取两个字段并将它们放入字典中。例如:
"food": [
"name": "pasta",
"type": "blabla",
"sauce": [
"name": "cream",
"url": "http://www...."
]
,
"name": "pizza",
"type": "bla",
"sauce": [
"name": "Tomato",
"url": "http://www...."
]
]
我想得到:
pasta: cream, pizza: Tomato
【问题讨论】:
【参考方案1】:dict comprehension
可以胜任:
data =
"food": [
"name": "pasta",
"type": "blabla",
"sauce": [
"name": "cream",
"url": "http://www...."
]
,
"name": "pizza",
"type": "bla",
"sauce": [
"name": "Tomato",
"url": "http://www...."
]
]
foods = data['food']
print( food['name']:food['sauce'][0]['name'] for food in foods)
【讨论】:
如果 json 是另一种文件或字符串格式,则必须使用json.load(file)
或 json.loads(string)
:类似于 import json; json.load("foods.json")
"food": [ "name": "pasta", "type": "blabla", "sauce": [ "name": "cream", "url": "@ 987654321@...." "name": "Tomato", "url": "www...." ] , "name": "pizza", "type": "bla" , "sauce": [ "name": "Tomato", "url": "www...." ] ] 如果我添加另一种酱汁,我想得到:pasta: cream Tomato ,披萨:番茄以上是关于如何在 Python 中解析 JSON 并将 2 个字段放入字典中? [复制]的主要内容,如果未能解决你的问题,请参考以下文章
React Native - 如何解析 json 数据并将其设置在状态对象中