xp1632 / DFKI_working_log

0 stars 0 forks source link

All about `JSON` #31

Open xp1632 opened 7 months ago

xp1632 commented 7 months ago

1. Create JSON

# Prepare list of dictionaries for Json
people = [
    {"name": "Alice", "age": 30, "occupation": "Engineer"},
    {"name": "Bob", "age": 25, "occupation": "Designer"},
    {"name": "Charlie", "age": 22, "occupation": "Student"}
]

# Use json module to convert list to JSON format
import json
json_string = json.dumps(people, indent=2)  # Indentation for readability

# Save json string to file
with open("people.json", "w") as json_file:
    json_file.write(json_string)

2. Access certain items in JSON

[
  {
    "name": "Alice",
    "age": 30,
    "occupation": "Engineer"
  },
  {
    "name": "Bob",
    "age": 25,
    "occupation": "Designer"
  },
  {
    "name": "Charlie",
    "age": 22,
    "occupation": "Student"
  }
]

3. Display JSON in jupyter

from IPython.display import display, JSON
data = {"name": "John", "age": 30}
display(JSON(data))

Running this code will display the JSON data in the output of a notebook cell.