0

I am trying to extract multiple objects from the same JSON file. My JSON file content looks something like this:

{"business_id": "1",
 "Accepts Credit Cards": true,
 "Price Range": 1,
 "type": "food"}
{"business_id": "2",
 "Accepts Credit Cards": true,
 "Price Range": 2,
 "type": "cloth"}
{"business_id": "3",
 "Accepts Credit Cards": false,
 "Price Range": 3,
 "type": "sports"}

I am trying the below code which works fine for a file containing only one JSON object.

import json

with open("business.json") as json_file:
    json_data = json.load(json_file)
    print(json_data)

How can I solve this problem? I did not find any solution for parsing JSON data from the same file.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Arighna
  • 89
  • 2
  • 9
  • 1
    Are you allowed fix your file? If you changed your file to be an array of json objects, it would work fine. – Paul Hicks Nov 19 '14 at 21:33
  • The file is not valid JSON as a whole. One simple solution would be to put `[` and the beginning of the file and `]` at the end to make it one big array. Then you could parse it as JSON and extract the individual pieces. – BrenBarn Nov 19 '14 at 21:34
  • You'd need a couple of commas too :) – Paul Hicks Nov 19 '14 at 21:34
  • And there are more closing braces than opening braces... – unutbu Nov 19 '14 at 21:36
  • @BrenBarn this is a small part of the whole object. The one I have used is valid as it works for single object. But it does not work for multiple JSON. Making it a list is not possible as there are total 70k objects like that. – Arighna Nov 20 '14 at 01:59
  • @unutbu would this work for the below data? Actually I took an example of multiple JSON objects in the same file. but the code which parse one object per file does not work for multiple objects in the same file {"business_id": "1", "Accepts Credit Cards": true, "Price Range": 1, "type": "food"} {"business_id": "2", "Accepts Credit Cards": true, "Price Range": 2, "type": "cloth"} {"business_id": "3", "Accepts Credit Cards": false, "Price Range": 3, "type": "sports"} – Arighna Nov 20 '14 at 04:16
  • The linked solution works when the JSON strings are concatenated with no whitespace in between. The solution can be made to work when there are spaces by stripping the `buffer` before decoding. I've posted the [code to do this here](http://stackoverflow.com/a/27040050/190597). – unutbu Nov 20 '14 at 12:50

0 Answers0