Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JSON to multiple dictionaries

I have a JSON data as follows

 '{"item_id": "0", "start": "2015-06-01 00:00:00", "target": [1.5, 1.545, 6.79, ]}\n{"item_id": "1", "start": "2015-06-01 00:00:00", "target": [254.7725, 136.0975, 181.28, 167.09, 206.25, 147.2075, ]}\n{"item_id": "3", "start": "2015-06-01 00:00:00", "target": [361.13, 254.925, 160.05, 0.0, 255.915, 95.37, 133.32, 297.33, 99.275, 357.5, 43.12, 118.58, 99.0, 348.48, 79.2, 141.625]}'

How do I create a list of dictionaries from this json?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It looks like there’s some trailing commas in some of the lists, but removing those, you can use .split() to split the string into individual JSON blobs, and then apply json.loads() to each of those blobs as you would with any other JSON string:

[json.loads(item) for item in data.split("\n")]

This outputs:

[
 {'item_id': '0', 'start': '2015-06-01 00:00:00', 'target': [1.5, 1.545, 6.79]},
 {'item_id': '1', 'start': '2015-06-01 00:00:00', 'target': [254.7725, 136.0975, 181.28, 167.09, 206.25, 147.2075]},
 {'item_id': '3', 'start': '2015-06-01 00:00:00', 'target': [361.13, 254.925, 160.05, 0.0, 255.915, 95.37, 133.32, 297.33, 99.275, 357.5, 43.12, 118.58, 99.0, 348.48, 79.2, 141.625]}
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading