Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple json dictionaries python

Tags:

python

json

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"}]}
like image 294
Fawad Avatar asked Oct 26 '25 08:10

Fawad


1 Answers

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 )
like image 68
nigel222 Avatar answered Oct 28 '25 21:10

nigel222



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!