Python Forum
iterate and print json datas
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
iterate and print json datas
#1
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
Reply
#2
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  time setup for realtime plotting of serial datas at high sampling rate alice93 6 3,740 Jan-07-2022, 05:41 PM
Last Post: deanhystad
  iterate json and count enigma619 2 2,022 Mar-02-2020, 01:41 PM
Last Post: enigma619
  print python json dump onto multiple lines lhailey 2 19,828 Mar-02-2020, 12:47 PM
Last Post: vishalhule
  Datas are not insert into database aravinth 1 2,194 Dec-21-2019, 04:17 PM
Last Post: buran
  [split] Print JSON Dictionary to Excel? venukommu 1 2,293 Nov-15-2019, 09:33 PM
Last Post: micseydel
  Print a JSON file mrobie 5 3,387 May-31-2019, 09:38 PM
Last Post: Yoriz
  How to put together datas into a file? Krszt 1 1,915 Nov-07-2018, 04:06 PM
Last Post: ichabod801
  Plotting datas Krszt 2 2,379 Oct-31-2018, 03:29 PM
Last Post: Davis4109
  How to put together datas from different files Krszt 3 2,374 Oct-31-2018, 07:37 AM
Last Post: Krszt
  How to write datas into a file? Krszt 2 2,390 Oct-25-2018, 01:45 PM
Last Post: Krszt

Forum Jump:

User Panel Messages

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