如何在python中将列表转换为jsonarray

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19795012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:39:31  来源:igfitidea点击:

How to convert a list to jsonarray in python

pythonjson

提问by frazman

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?

基本上将上面转换为jsonarray?

Is there an inbuilt method, function in python to "dump" array into json array?

是否有内置方法,python 中的函数将数组“转储”到 json 数组中?

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

另请注意,我不希望在我的文件中序列化“L”。

采纳答案by Martijn Pieters

Use the jsonmoduleto produce JSON output:

使用json模块生成 JSON 输出:

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).

这会将 JSON 结果直接写入文件(如果文件已存在,则替换任何先前的内容)。

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

如果您需要 Python 本身的 JSON 结果字符串,请使用json.dumps()(已添加s, for 'string'):

json_string = json.dumps(row)

The Lis just Python syntax for a long integer value; the jsonlibrary knows how to handle those values, no Lwill be written.

L只是长整数值的 Python 语法;该json库知道如何处理这些值,没有L将被写入。

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]]]'

回答by virtuexru

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