NAS_2339
NAS_2339

Reputation: 353

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?

Upvotes: 1

Views: 66

Answers (1)

BrokenBenchmark
BrokenBenchmark

Reputation: 19242

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]}
]

Upvotes: 1

Related Questions