1

I am reading a file that contains JSON separated by commas. So for example

{
  ...JSON
},
{
  ...JSON
},
{
  ...JSON
}

I know for sure they are separated by commas but not sure it they are separated by newlines. This JSON can potentially all be on one line. But for sure they are separated by commas. I have not received that data yet. I am wondering how I can parse each JSON object and append it to a list.

pseudo code:

def source_parse(source_file):
   json_list = []
   with open(source_file) as source:
      json_source = source.readlines()
      # parse json_source
      json_list.append(json_obj)
Liondancer
  • 15,721
  • 51
  • 149
  • 255

2 Answers2

7

That's not valid JSON, it is missing the [...] brackets to make it a list.

You could add those manually:

with open(source_file) as source:
    json_source = source.read()
    data = json.loads('[{}]'.format(json_source))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

you can parse the data to dict by following this link. Parsing values from a JSON file using Python?

and convert the dict to list by the

.items()

function to the parsed dictionary.

Hope this one solves the problem. Good luck.

Community
  • 1
  • 1