Python Forum

Full Version: iterate and print json datas
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi

i've a problem to iterate a json file

My Json
{
  "name": "value1",
  "surname": "value2",
  "size": "value3",
  "age": "value4",
  "update": false
}
I want to iterate with python this json and print for each key, the value associated.

try:
    file = json.load(json_file)
except ValueError:
    logging.critical("Data were not valid json for %s", file)
    sys.exit(1)

for key, value in file.items():
    try:
        name = value["name"]
    except KeyError:
        logging.error("No name defined")
        sys.exit(1)
    print (name)
But I've the error: TypeError: string indices must be integers

I want to do the same for others values: age, surname, update..

I'm sure it's a stupid error but I don't see the problem.
Does anyone have an idea for this?
Thanks

Alex
there is something else in your file - check your json file. Your code should work if json was like you say

source = """{
  "name": "value1",
  "surname": "value2",
  "size": "value3",
  "age": "value4",
  "update": false
}"""

import json
data = json.loads(source)
for key, value in data.items():
    print(f'{key} --> {value}')
Output:
name --> value1 surname --> value2 size --> value3 age --> valu