Gru*_*uck 23 python django json dictionary
我一直在寻找这个问题的答案,而我似乎无法追踪它.也许晚上来得太晚才能找出答案,所以我在这里转向优秀的读者.
我有以下一些JSON数据,我从CouchDB记录中提取出来:
"{\"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\"},"
Run Code Online (Sandbox Code Playgroud)
这些数据存储在Python dict locations中,位于名为' my_plan' 的dict中的键' ' 下.我想将这些数据从CouchDB转换为Python dict,所以我可以在Django模板中执行以下操作:
{% for location in my_plan.locations %}
<tr>
<td>{{ location.place }}</td>
<td>{{ location.locationDate }}</td>
</tr>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
我已经找到了很多关于将dicts转换为JSON的信息,但是没有其他方面可以反过来.
Mik*_*ham 37
使用该json模块加载JSON.(2.6之前使用第三方simplejson模块,它具有相同的API.)
>>> import json
>>> s = '{"foo": 6, "bar": [1, 2, 3]}'
>>> d = json.loads(s)
>>> print d
{u'foo': 6, u'bar': [1, 2, 3]}
Run Code Online (Sandbox Code Playgroud)您的实际数据无法以这种方式加载,因为它实际上是由逗号和尾随逗号分隔的两个JSON对象.您需要将它们分开或以其他方式处理.
Ale*_*lli 18
您显示的字符串不是JSON编码的对象(Python字典的eqv) - 更像是一个没有括号的数组(eqv到列表),并且末尾有一个额外的逗号.所以(使用simplejson进行版本可移植性 - json2.6中的标准库当然也没问题! - ):
>>> 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'}]
Run Code Online (Sandbox Code Playgroud)
如果你真的想要一个字典,你必须指定如何处理这两个未命名的项目,即你想要拍哪些任意键......?