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

How to parse a string of multiple jsons without separators in python?

Given a single-lined string of multiple, arbitrary nested json-files without separators, like for example:

contents = r'{"payload":{"device":{"serial":213}}}{"payload":{"device":{"serial":123}}}'

How can contents be parsed into an array of dicts/jsons ? I tried

df = pd.read_json(contents, lines=True)

But only got a ValueError response:

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

ValueError: Unexpected character found when decoding array value (2)

>Solution :

You can split the string, then parse each JSON string into a dictionary:

import json

contents = r'{"payload":{"device":{"serial":213}}}{"payload":{"device":{"serial":123}}}'

json_strings = contents.replace('}{', '}|{').split('|')
json_dicts = [json.loads(string) for string in json_strings]

Output:

[{'payload': {'device': {'serial': 213}}}, {'payload': {'device': {'serial': 123}}}]
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