0

I'm on python 3.8. Here an example JSON file i'm working with:

{
  "dict1": {
      "text": "here",
      "more text": "here too"
      },
  "dict2": {
      "cool": "text",
      "filler": "element"
      }
}

I'm eventually gonna be working with multiple dicts and won't always know the names of them. When I do this:

import json

with open("jsonfile.json", "r") as file:
    data = json.load(file)
for element in data:
    if element is dict:
        print(element)

It prints nothing. No error messages, just nothing. Thank you in advance!

Kronifer
  • 25
  • 4

2 Answers2

1
import json

with open("jsonfile.json", "r") as file:
    data = json.load(file)
for element in data.values():
    if isinstance(element, dict):
        print(element)
pts
  • 80,836
  • 20
  • 110
  • 183
-1

if you want to iterate the values of a dictionary, use dict.values()

d = {
  "dict1": {
      "text": "here",
      "more text": "here too"
      },
  "dict2": {
      "cool": "text",
      "filler": "element"
      }
}

for element in d.values():
    if type(element) == dict:
        print(element)
{'text': 'here', 'more text': 'here too'}
{'cool': 'text', 'filler': 'element'}
MarcoP
  • 1,438
  • 10
  • 17