Python JSON Handle multiple root elements

Problem

Sometimes you just want to implement a small tool, you have some experience in the technologies you want to use, and then boom, something explodes in your face.

This article is about something like this.

I wanted to experiment with Cryptocurrency trading. For that I used an exchange I´m already registered at (not naming it).

Going through the documentation it seemed okay, should not be too hard to make a small bot.
While I was implementing it, my bot crashed quickly and regularly and I didn´t understand why.

Until I found out, that they go against the JSON Standard, which allows only one root element. But I got multiples. Damn.

Solution

Researching on Google I couldn´t quickly find a package that can help in python, so I created one: https://pypi.org/project/splicejsonmultipleroots-thestrugglingdeveloper/.

If you want to learn how to create such a python package yourself: https://www.thestrugglingdeveloper.com/2021/01/04/create-python-package/

The package doesn’t handle any errors, I just wanted a quick solution and share it.

If you want to contribute please feel free to send a pr: https://github.com/thestrugglingdeveloper/splicejsonmultipleroots

Back to the solution:

Algorithm

1. Remove appended or prepended whitespace
2. Iterate over the given string, extract JSON string is finished
3. Return array of JSON strings

Remove appended or prepended whitespace

This seems to be self-explaining. Removing the whitespace at the beginning and the end of the string makes sure there is no waste. And prevents parsing errors.

Iterate over the given string, extract JSON string is finished

The method runs a simple for loop over the string given. It uses string comparison to count the number of opening and closing curly brackets (“{}”).
When the counter reaches 0, the number of curly brackets are equal and a complete root element was found.

The string is then copied to a string of arrays and the process continued until no more matches are found.

Return array of JSON strings

After the last set of matching curly brackets were found, the code simple returns the array of all found JSON strings.

Result

The user has at the end the array of JSON string and can process them in any way they want.

In my project I handle each array item separately, parse it to get a JSON Object and extract the price information.

Notes

As I mentioned on purpose I did not implement error handling. It was for a quick and easy solution to test my mvp.

I plan to implement basic error handling on the package to make it more usable for others. And because it feels right to do so.

If you have issues with the package, want to contribute or just chat about something, feel free to comment here or contact me.

Best,

Frank

Leave a Reply