Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Parse JSON multiple objects
#1
I'm having trouble parsing multiple objects within a JSON array. I can get my code to work, but I have to manipulate the JSON file which I shouldn't have to do.

I'm on Python 3, and here's my code:

import json

tradingList = []
print
with open('party.json') as f:
    for jsonObj in f:
        tradingDict = json.loads(jsonObj)
        tradingList.append(tradingDict)

print
for trade in tradingList:
    print(trade["id"], trade["name"])
Here's my original JSON data:

Output:
[{"id":3090,"name":"Wegmans","aventionId": null}, {"id":1156,"name":"Giant","aventionId": null}, {"id":4340,"name":"Safeway","aventionId": null}, {"id":5965,"name":"Publix","aventionId":[]}]
That results in an error "list indices ust be integers or slices, not str".

If I delete the square brackets (array), delete the commas, insert hard returns after each line the data comes back correct. Here's how I reformat the JSON:
Output:
{"id":3090,"name":"Wegmans","aventionId": null} {"id":1156,"name":"Giant","aventionId": null} {"id":4340,"name":"Safeway","aventionId": null} {"id":5965,"name":"Publix","aventionId":[]}
Here's the desired output:

Output:
3090 Wegmans 1156 Giant 4340 Safeway 5965 Publix
Any help is appreciate, thank you!
Reply
#2
Don't use the quote button to post your code - see BBCode to know more about proper code tags usage.
pyzyx3qwerty
"The greatest glory in living lies not in never falling, but in rising every time we fall." - Nelson Mandela
Need help on the forum? Visit help @ python forum
For learning more and more about python, visit Python docs
Reply
#3
Sorry about that, corrected below:

Code:

import json

tradingList = []
print
with open('party.json') as f:
for jsonObj in f:
tradingDict = json.loads(jsonObj)
tradingList.append(tradingDict)

print
for trade in tradingList:
print(trade["id"], trade["name"])
Error resulting from original JSON file:

Error:
TypeError: list indices must be integers or slices, not str
Reply
#4
I fixed your tags in the original post. In the second post your indentation is wrong.
Also these print on line 4 and 10 will cause error. If they don't - you are using python2 and you should be using python3

Back to original post - you are overdoing things
1. Read json - get list of dicts
2.iterate over the list and parse each dict

import json

with open('party.json') as f:
    data = json.load(f)
for trade in data:
    print(trade["id"], trade["name"])
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
#5
Thank you, buran. I'm on Python 3.7.6 with Spyder and am not receiving errors as indicated. I used your example and am returning
Error:
JSONDecodeError: Extra data
Reply
#6
check your json file, there is something extra
with the example data in first post it works
see: https://repl.it/repls/SmoggyBlueState
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
#7
if you are unsure of the validity of the json data then copy paste it into a online validator first, then you can least start knowing the data is kosher
Regards
-------- *
“Outside of a dog, a book is man's best friend. Inside of a dog it's too dark to read.”
Reply
#8
print(type(data))
will tell you which type of variable is data
string, integer, json etc..
Reply
#9
@pythonlearner1 - yes type will tell you just that, the type of the "data", but that will not tell you if the contents of the data is valid (and hence my suggestion to use a json validator if unsure first), in the case of the original posting, the variables the developer used can be tested as you say, but when the json he is reading is dumped into that variable it will just tell him the variable is of type "dict" or "list" or "str" for example, it wont tell him that the json is valid json necessarily, or that its presentation is without escape characters (encoding) depending on the method chosen or the package used - (there are a plethora of json parsers and validator packages in python), also the user was trying to iterate over a list in his second piece of code using a "dictionary" style "keywords", whereas a List requires indexes or an index range for splicing.
Regards
-------- *
“Outside of a dog, a book is man's best friend. Inside of a dog it's too dark to read.”
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  parse json field from csv file lebossejames 4 668 Nov-14-2023, 11:34 PM
Last Post: snippsat
  [split] Parse Nested JSON String in Python mmm07 4 1,413 Mar-28-2023, 06:07 PM
Last Post: snippsat
  Trying to parse only 3 key values from json file cubangt 8 3,338 Jul-16-2022, 02:05 PM
Last Post: deanhystad
  geojson to json --missing multiple row output yoshi 9 2,654 Mar-06-2022, 08:34 PM
Last Post: snippsat
  Problem to parse a json enigma619 3 2,342 Dec-04-2020, 08:16 AM
Last Post: enigma619
  How to parse JSON DIC? ogautier 4 2,187 Sep-15-2020, 06:03 PM
Last Post: ogautier
  Looking for help in Parse multiple XMLs and update key node values and generate Out.. rajesh3383 0 1,847 Sep-15-2020, 01:42 PM
Last Post: rajesh3383
  How can i parse a log file to JSON. menarcarlos 2 2,373 May-26-2020, 10:23 AM
Last Post: buran
  print python json dump onto multiple lines lhailey 2 19,650 Mar-02-2020, 12:47 PM
Last Post: vishalhule
  How to serialize custom class objects in JSON? Exsul1 4 3,432 Sep-23-2019, 08:27 AM
Last Post: wavic

Forum Jump:

User Panel Messages

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