user13075538
user13075538

Reputation:

Loop via list of dicts in a JSON file

Cant seem to figure out why my loop of a json file containing a list of dicts is recognizing the '[' and ']' symbols as strings. Usually a loop would just print out the values within a list.

This is the file structure

[
{"merch_name": "amazon.com", "link": "http://amazon.com"},
{"merch_name": "ebay.com", "link": "http://ebay.com"},
{"merch_name": "amazon.co.jp", "link": "http://amazon.co.jp"}
]

and heres the code for the loop

with open('velreiz9.json', 'r') as web_list:
    for merch in web_list:

        print(merch)

As you can see the debugger treats the '[' as a string debugger

Upvotes: 1

Views: 53

Answers (2)

Patrick Artner
Patrick Artner

Reputation: 51623

You only have a string from a file here, with

with open('velreiz9.json', 'r') as web_list:
    for merch in web_list:

you iterate the files text line - wise - you do not yet operate on a python list but just a string.

The first line ends at the \n after the first '['. To iterate the data as python objects you need to parse the json:

with open("f.txt", "w") as f:
  f.write("""[
{"merch_name": "amazon.com", "link": "http://amazon.com"},
{"merch_name": "ebay.com", "link": "http://ebay.com"},
{"merch_name": "amazon.co.jp", "link": "http://amazon.co.jp"}
]""")

import json
from pprint import pprint

with open("f.txt") as f:
    as_obj = json.load(f) # this loads the text into an python object to use
    pprint(as_obj)    
  

Output:

# formatting due to pprint
[{'link': 'http://amazon.com', 'merch_name': 'amazon.com'},
{'link': 'http://ebay.com', 'merch_name': 'ebay.com'},
{'link': 'http://amazon.co.jp', 'merch_name': 'amazon.co.jp'}]

Upvotes: 2

Akhilesh_IN
Akhilesh_IN

Reputation: 1307

import json

with open("velreiz9.json",'r') as f:
    web_list = json.load(f)
    for merch in web_list:
        print(merch)

output:

{'merch_name': 'amazon.com', 'link': 'http://amazon.com'}
{'merch_name': 'ebay.com', 'link': 'http://ebay.com'}
{'merch_name': 'amazon.co.jp', 'link': 'http://amazon.co.jp'}

Upvotes: -1

Related Questions