将Python字典转换为JSON数组 [英] Converting Python Dictionary to JSON Array

查看:68
本文介绍了将Python字典转换为JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个类似这样的Python字典:

I currently have a Python Dictionary that looks something like this:

OrderedDict([('2017-07-24', 149.7619), ('2017-07-25', 150.4019), ('2017-07-26', 151.1109), ...

$我正在这样转换为JSON的b
$ b

that I am converting to JSON like so:

one_yr = json.dumps(priceDict)

当前,我正在像这样通过循环遍历从SQL查询向字典添加值:

Currently I am adding values to the dictionary from an SQL query by looping through it like so:

for i in query:
    date = i[0] 
    close = i[1]
    priceDict[date] = close

问题是,这将返回JSON对象,然后

The problem is that this returns a JSON object, that i then have to convert to a JSON array.

我想知道是否可以直接将Python词典直接转换为JSON数组吗?

I am wondering if I can just convert my Python Dictionary to a JSON array directly? Thanks.

推荐答案

json.dumps(list(priceDict.items()))

但是为什么您首先拥有 OrderedDict ?如果将传递给 OrderedDict 的同一列表传递给 json.dumps ,它将生成您的数组:

But why do you have an OrderedDict in first place? If you pass the same list you passed to OrderedDict to json.dumps it will generate your array:

json.dumps([('2017-07-24', 149.7619), ('2017-07-25', 150.4019),....])

不需要 OrderedDict 在这种情况下

这篇关于将Python字典转换为JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆