如何在python中将列表转换为jsonarray [英] How to convert a list to jsonarray in python
问题描述
我有以下格式的行:
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]]]
基本上将上面转换成jsonarray吗?
Basically converting above into a jsonarray?
是否有内置的方法,可以在python中将数组转储"到json数组中?
Is there an inbuilt method, function in python to "dump" array into json array?
还请注意,我不希望在文件中序列化"L".
Also note that I don't want "L" to be serialized in my file.
推荐答案
使用 json
模块产生JSON输出:
Use the json
module to produce JSON output:
import json
with open(outputfilename, 'wb') as outfile:
json.dump(row, outfile)
这会将JSON结果直接写入文件(如果文件已经存在,则替换以前的任何内容).
This writes the JSON result directly to the file (replacing any previous content if the file already existed).
如果您需要Python本身中的JSON结果字符串,请使用json.dumps()
(为s
):
If you need the JSON result string in Python itself, use json.dumps()
(added s
, for 'string'):
json_string = json.dumps(row)
L
只是用于长整数值的Python语法; json
库知道如何处理这些值,因此不会编写任何L
.
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.
演示字符串输出:
>>> import json
>>> row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
>>> json.dumps(row)
'[1, [0.1, 0.2], [[1234, 1], [134, 2]]]'
这篇关于如何在python中将列表转换为jsonarray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!