如何解析JSON并在Python中将2个字段放在字典中?

时间:2018-06-10 12:08:17

标签: python json python-3.x dictionary

我想解析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 个答案:

答案 0 :(得分:2)

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