4

I have a json file with multiple json dictionaries: the format is as following

{"x":"1", "y":"2", "z": "3"}{"x": "2","y":"3", "z":"4"}{"x":"3", "y":"4", "z":"5"}

How can I convert this to one json dictionary format as following:

{"items":[{"x":"1", "y":"2", "z": "3"},{"x": "2","y":"3", "z":"4"},{"x":"3", "y":"4", "z":"5"}]}
3
  • 8
    That file is broken. Return it to sender with kind regards to provide valid JSON, or at least a sane format. Commented May 3, 2016 at 11:27
  • Unfortunately I have generated this file myself from a python script which gets this data from a website. Commented May 3, 2016 at 11:59
  • 1
    It's very, very common to find multiple JSON elements concatenated in one file. People do not read the JSON specification or the Python json module doc. quote: "Unlike pickle and marshal, JSON is not a framed protocol so trying to serialize more objects with repeated calls to dump() and the same fp will result in an invalid JSON file. " Commented May 3, 2016 at 13:25

1 Answer 1

2

Already mostly answered here: Importing wrongly concatenated JSONs in python

That shows you how to pick up each JSON element from a concatenated list of them (which is not valid JSON) using json.JSONDecoder method raw_decode(). The rest is a simple matter of concatenating strings '{"items":[', element1, ",", element2, ... "]" or alternatively, accumulating them as a list, wrapping that with a one-item dict and if required, dumping that json as a string with json.dumps

OK expanding on that

import json
d = json.JSONDecoder()

# get your concatenated json into x, for example maybe
x = open('myfile.json','r').read()

jlist=[]
while True:
   try:
      j,n = d.raw_decode(x) 
      jlist.append(j)
   except ValueError: 
      break
   x=x[n:]

# my original thought was
result = '{"items":[' + 
     ','.join( [ str(s) for s in jlist] ) +
     ']'

# but this is neater
result = json.dumps( { "items":jlist })

# and of course if you want it for programmatic use, just
result_as_json = dict( items=jlist )
Sign up to request clarification or add additional context in comments.

3 Comments

I visited the link, but it doesn't seem to help much. I am a newbie in Python.
import json data = [] with open('c:\\users\\fawads\\desktop\\short.json') as f: data = f.read() d = json.JSONDecoder() d.raw_decode(data) with open('c:\\users\\fawads\\desktop\\data.json', 'w') as outfile: json.dump(data, outfile) I tried this, but it didnt help.
Thanks a lot. I used the above code and things are now in proper shape :)

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.