-1

I want to parse JSON file and get two fields from the JSON and put them in a dictionary. For example:

{
    "food": [{
            "name": "pasta",
            "type": "blabla",
            "sauce": [{
                    "name": "cream",
                    "url": "http://www...."
                }
            ]
        }, {
            "name": "pizza",
            "type": "bla",
            "sauce": [{
                    "name": "Tomato",
                    "url": "http://www...."
                }
            ]
        }
    ]
}

And I want to get:

{pasta: cream, pizza: Tomato}
Omar Einea
  • 2,478
  • 7
  • 23
  • 35
EladS
  • 29
  • 1
  • 3

1 Answers1

1

A dict comprehensioncan do the job:

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})
Gelineau
  • 2,031
  • 4
  • 20
  • 30
  • 2
    if the json is in another file or string format, you'd have to use `json.load(file)` or `json.loads(string)`: something like `import json; json.load("foods.json")` –  Jun 10 '18 at 12:23
  • "food": [{ "name": "pasta", "type": "blabla", "sauce": [{ "name": "cream", "url": "http://www...." } { "name": "Tomato", "url": "http://www...." } ] }, { "name": "pizza", "type": "bla", "sauce": [{ "name": "Tomato", "url": "http://www...." } ] } ] } And if I add another sauce and I want to get: {pasta: cream Tomato, pizza: Tomato} – EladS Jun 10 '18 at 14:05