Ask Your Question
2

How do I work with nested JSON in Python?

asked 2023-07-18 06:35:14 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-07-18 06:39:01 +0000

david gravatar image

To work with nested JSON in Python, you can use the built-in json module.

  1. Import the json module:
import json
  1. Load the JSON string or file into a Python object using the json.loads() or json.load() method:
data = '{"name": "John", "age": 30, "city": "New York", "skills": {"language": "Python", "database": "MySQL"}}'

python_obj = json.loads(data)

or

with open('data.json') as f:
    python_obj = json.load(f)
  1. Access the nested elements using key-value pairs:
print(python_obj['name'])  # John
print(python_obj['skills']['language'])  # Python
  1. Modify the nested elements:
python_obj['skills']['database'] = 'PostgreSQL'

print(python_obj['skills'])  # {'language': 'Python', 'database': 'PostgreSQL'}
  1. Convert the Python object back to a JSON string using the json.dumps() method:
new_data = json.dumps(python_obj)

print(new_data)

OUTPUT:

{'name': 'John', 'age': 30, 'city': 'New York', 'skills': {'language': 'Python', 'database': 'PostgreSQL'}}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-18 06:35:14 +0000

Seen: 12 times

Last updated: Jul 18 '23