How to convert a list of numbers to jsonarray in Python

PythonJson

Python Problem Overview


I have a row in following format:

row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]

Now, what I want is to write the following in the file:

[1,[0.1,0.2],[[1234,1],[134,2]]]

Basically converting above into a jsonarray?

Is there an built-in method, library, or function in Python to "dump" array into json array?

Also note that I don't want "L" to be serialized in my file.

Python Solutions


Solution 1 - Python

Use the json module to produce JSON output:

import json

with open(outputfilename, 'wb') as outfile:
    json.dump(row, outfile)

This writes the JSON result directly to the file (replacing any previous content if the file already existed).

If you need the JSON result string in Python itself, use json.dumps() (added s, for 'string'):

json_string = json.dumps(row)

The L is just Python syntax for a long integer value; the json library knows how to handle those values, no L will be written.

Demo string output:

>>> import json
>>> row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
>>> json.dumps(row)
'[1, [0.1, 0.2], [[1234, 1], [134, 2]]]'

Solution 2 - Python

import json
row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
row_json = json.dumps(row)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfrazmanView Question on Stackoverflow
Solution 1 - PythonMartijn PietersView Answer on Stackoverflow
Solution 2 - PythonvirtuexruView Answer on Stackoverflow