python模块list 转json字符串,如何在python中将列表转换为jsonarray

该博客介绍如何使用Python内置的json模块将包含长整型(L)的数据转换为JSON数组,并写入文件。通过json.dumps()和json.dump()函数,可以轻松实现数据的序列化,同时不会在输出中包含'L'标记。
摘要由CSDN通过智能技术生成

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 inbuilt method, function in python to "dump" array into json array?

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

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值