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.
We can convert a list to the JSON array using the JSONArray. toJSONString() method and it is a static method of JSONArray, it will convert a list to JSON text and the result is a JSON array.
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
In Python, you can create JSON string by simply assigning a valid JSON string literal to a variable, or convert a Python Object to JSON string using json. loads() function.
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]]]'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With