将JSON转换为Python dict [英] Converting JSON into Python dict

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

问题描述

我一直在寻找这个问题的答案,我似乎无法追踪它。也许晚上太晚了解答案,所以我转向这里的优秀读者。

I've been searching around trying to find an answer to this question, and I can't seem to track it down. Maybe it's too late in the evening to figure the answer out, so I turn to the excellent readers here.

我有以下JSON数据我正在拉出的CouchDB记录:

I have the following bit of JSON data that I am pulling out of a CouchDB record:

"{\"description\":\"fdsafsa\",\"order\":\"1\",\"place\":\"22 Plainsman Rd, Mississauga, ON, Canada\",\"lat\":43.5969175,\"lng\":-79.7248744,\"locationDate\":\"03/24/2010\"},{\"description\":\"sadfdsa\",\"order\":\"2\",\"place\":\"50 Dawnridge Trail, Brampton, ON, Canada\",\"lat\":43.7304774,\"lng\":-79.8055435,\"locationDate\":\"03/26/2010\"},"

该数据存储在一个名为my_plan的dict中的位置下的Python dict内。我想将这个数据从CouchDB隐藏成一个Python dict,所以我可以在Django模板中执行以下操作:

This data is stored inside a Python dict under the key 'locations' in a dict called 'my_plan'. I want to covert this data from CouchDB into a Python dict so I can do the following in a Django template:

{% for location in my_plan.locations %}                                                           
<tr>
    <td>{{ location.place }}</td>
    <td>{{ location.locationDate }}</td>
</tr>

{% endfor %}

我发现很多信息将dict转换成JSON,但是没有回到另一种方式

I've found lots of info on converting dicts to JSON, but nothing on going back the other way

提前感谢帮助!

推荐答案

您显示的字符串不是JSON编码的对象(对于Python dict)(而不是Python dict) - 更像是一个没有括号的数组(方程式为一个列表),最后还有一个杂散的逗号。所以(使用 simplejson 进行版本可移植性 - 2.6中的标准库的 json 当然也是可以的! - ):

The string you show is not a JSON-coded object (eqv to a Python dict) — more like an array (eqv to a list) without brackets and with a stray extra comma at the end. So (using simplejson for version portability — the standard library's json in 2.6 is fine too of course!-):

>>> import simplejson
>>> js = "{\"description\":\"fdsafsa\",\"order\":\"1\",\"place\":\"22 Plainsman Rd, Mississauga, ON, Canada\",\"lat\":43.5969175,\"lng\":-79.7248744,\"locationDate\":\"03/24/2010\"},{\"description\":\"sadfdsa\",\"order\":\"2\",\"place\":\"50 Dawnridge Trail, Brampton, ON, Canada\",\"lat\":43.7304774,\"lng\":-79.8055435,\"locationDate\":\"03/26/2010\"},"
>>> simplejson.loads('[%s]' % js[:-1])
[{'description': 'fdsafsa', 'order': '1', 'place': '22 Plainsman Rd, Mississauga, ON, Canada', 'lat': 43.596917500000004, 'lng': -79.724874400000004, 'locationDate': '03/24/2010'}, {'description': 'sadfdsa', 'order': '2', 'place': '50 Dawnridge Trail, Brampton, ON, Canada', 'lat': 43.730477399999998, 'lng': -79.805543499999999, 'locationDate': '03/26/2010'}]

如果你真的想要一个dict,你必须指定如何处理这两个未命名的项目,即你要拍摄什么特殊的键他们...?

If you really want a dict you'll have to specify how to treat these two unnamed items, i.e., what arbitrary keys you want to slap on them...?

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

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