Join the Stack Overflow Community
Stack Overflow is a community of 6.3 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

First time working with around with json files. I am using the following code to read through a json file in python:

l = []
with codecs.open('file.json', 'r', encoding='utf-8') as jsonfile:
    for line in jsonfile:
        data = json.loads(line)
        l.append(data)

The list was made because when I was opening the file without the first and last line, every time I accessed data, only the last element was returned. For example,

with codecs.open('file.json', 'r', encoding='utf-8') as jsonfile:
    for line in jsonfile:
        data = json.loads(line)

data['item']

would only give the last item of the json dataset, instead of returning all the items in it. Now, there are more dictionaries(nested) inside the 'l' list making navigation through the dataset a bit complicated. Are there any recommendations for having to read through the file without lists where the file is not overwritten so that it stops giving me the last line for each dictionary key?

share|improve this question

You should read the doc of the json module , you need to json.loads() on the entire file not a line

data = json.load(open('file.json'))
share|improve this answer
    
Or the slightly more concise: with open(json_file) as f: data = json.load(f) – BringMyCakeBack Nov 18 '14 at 23:11
    
just saw it in the doc, I tried to find a version where you just put a file name but no -_- – Ludovic Viaud Nov 18 '14 at 23:13

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.