2

I have a list of JSON files saved to disk that I would like to read. Sometimes the JSON files span more than one line and so, I think that a simple list comprehension that loops over open(file,'rb').readlines() will fail.

The files are surrounded in brackets and so passing them to json.load or json.loads won't work.

An example file would be:

[{key:value,key2:value2},{morekeys:morevalues},{evenmorekeys,evenmorevalues}]

What is the best/ most Pythonic way to read a saved list of JSON entries when the entries span more than one line?

3
  • Can you show a snippet of what your files look like? Why wouldn't they be loadable json? What added invalid formatting to them? Newlines don't matter in json. Commented Nov 24, 2012 at 1:59
  • The files begin with [ and end with ]. Answer annotated. Thanks for the suggestion. Commented Nov 24, 2012 at 2:00
  • 1
    But [] are valid json arrays. It sounds like you have an array of objects. Commented Nov 24, 2012 at 2:02

1 Answer 1

4

Your example is valid json. [] define json arrays. What you have is an array of objects:

with open("myFile.json") as f:
    objects = json.load(f)
Sign up to request clarification or add additional context in comments.

2 Comments

Your code work for a single file, not a list of files
@Julien the original question asked how to read a given file that defines an array of objects. The OP only referenced having multiple files with this format. Reading more than one file is not a json problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.