-6

I have a JSON file that contains multiple objects

{
  "Elements": [
    {
      "name": "Hydrogen",
      "symbol": "H"
    },
        {
      "name": "Lithium",
      "symbol": "Li"
    },
        {
      "name": "Sodium",
      "symbol": "Na"
    }
  ]
}

I want to be able to search them using the name but only a single one. So far, I've been able to read all of the elements together with an output like

Hydrogen
Lithium
Sodium

but I want to only read one of the objects not all of them. My python code for this so far is

import json

f = open('elements.json')
data = json.load(f)

for element in data['Elements']:
    print(element['name'])

Ary_2121
  • 25
  • 6

2 Answers2

0

Try adding adding an if parameter to check if its the desired item that your looking for, then just record all of its information.

import json

with open('elements.json') as f:
   data = json.load(f)
choice = input("Choose element: ")

for element in data['Elements']:
   if element['name'] == choice:
       for x, y in element.items():
         print(x.title() + "-> " + y)
   
Maxim
  • 281
  • 2
  • 6
0

As far as i understood, you asked for a solution to get the first element with provided element name. Here it is:

def match(data, name):
        for element in data['Elements']:
            if element['name'] == name:
                return element

Another option: find first sequence item that matches a criterion

 def match(data, name):
        return next(element for element in data['Elements'] if element['name'] == name)
Ledorub
  • 146
  • 1
  • 9