-2

I want to know how to read a specific objects value from within a JSON object.

    "worker_01": {
        "data": {
            "name": "Juan",
            "manager": 0,
            "weight": 75,
            "positions": {
                "FOH": 1,
                "MOH": 1,
                "BOH": 1
            }
        }
    },

I know previously in Node.js I could read them by doing *.get(worker_01.data.name)* but python doesn't really allow that. I want to know how do I do something similar to that in python.

Here is my source code.

import json as js

data_json = open('hello.json')
data_worker = js.load(data_json)

for i in data_worker['worker_01']:
    print(i)
martineau
  • 119,623
  • 25
  • 170
  • 301
  • Please, show valid JSON – buran Nov 29 '21 at 21:40
  • well, it is somewhat similar in Python really, something like `data_worker['worker_01']['data']['name']`, as a type `data_worker` here is a python dictionary if you use `load`, also a bit related: I would suggest using `with` to open files – Matiiss Nov 29 '21 at 21:41
  • Buran, i just copied a snipet of the JSON file, so it wasn't the correct format. Matiiss, thank you, this helped. works as i wanted it. – Carlos Gross Nov 29 '21 at 21:50
  • Once you have loaded the JSON, you work with the resulting structure of nested dictionaries and/or lists *the exact same way that you would, if the data came from anywhere else*. – Karl Knechtel Nov 29 '21 at 22:23

1 Answers1

1

In Python, you can read JSON as a big python dictionary with mini listed dictionaries in between them all. With that in mind, you can index specific attributes from the JSON. For example based on your JSON, if a user wanted to get data on a persons name, you would do data_worker['worker_01']['data']['name'] to get the output 'Juan'

Here is more resources for you to look at too! https://www.w3schools.com/python/python_json.asp https://www.codegrepper.com/code-examples/python/how+to+get+specific+data+from+json+using+python https://www.w3schools.com/python/python_dictionaries.asp

dawggy
  • 26
  • 2