Python Forum
Need help Understanding JSON
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need help Understanding JSON
#4
How a json file starts depends on what you write to the file.

json.dump([1, 2, 3, 4], file) writes a file that contains [1, 2, 3, 4].

json.dump({"one":1, "two":2, "three":3}, file) writes a file that contains {"one": 1, "two": 2, "three": 3}.

json.dump("hello", file) writes a file that contains "hello".

json.dump(42, file) writes a file that contains 42.

Look at my earlier post. It shows how to drill down and look at the object created by json.load() or json.loads().

Try running this code. Maybe it will help you understand.
import json

# Replace with name of your json file
with open("data.txt", "r") as f:
    data = json.load(f)

# data is a list, because the json file starts with "[" and ends with "]".
# We can index a list or loop through a list.  Here we loop.
for thing in data:
    # thing is a dictionary.  You can tell this because it starts with "{" and ends with "}".
    # It has keys "kind" and "entries".
    print(thing["kind"])
    for entry in thing["entries"]:
        # thing["entries"] is a list.
        for key in entry:
            # entry is a dictionary.  Here we loop through the dictionary keys which we use
            # to pretty print the dictionary values.
            print(f"    {key.title():20} {entry[key]}")
        print()
    print()
Reply


Messages In This Thread
Need help Understanding JSON - by quarinteen - Aug-15-2022, 01:29 PM
RE: Need help Understanding JSON - by deanhystad - Aug-15-2022, 02:48 PM
RE: Need help Understanding JSON - by quarinteen - Aug-15-2022, 04:27 PM
RE: Need help Understanding JSON - by deanhystad - Aug-15-2022, 08:33 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020