我一直在寻找这个问题的答案,而我似乎无法追踪它。也许晚上太晚才能找出答案,所以我转向优秀的读者。
我从CouchDB记录中获取了以下一些JSON数据:
"{\"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\"},"
此数据存储在名为“locations
”的字典中的密钥“my_plan
”下的Python字典中。我想将这些数据从CouchDB转换为Python dict,所以我可以在Django模板中执行以下操作:
{% for location in my_plan.locations %}
<tr>
<td>{{ location.place }}</td>
<td>{{ location.locationDate }}</td>
</tr>
{% endfor %}
我已经找到了很多关于将dicts转换为JSON的信息,但是没有其他方面可以反过来。
答案 0 :(得分: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]}
您的实际数据无法以这种方式加载,因为它实际上是由逗号和尾随逗号分隔的两个JSON对象。您需要将它们分开或以其他方式处理。
答案 1 :(得分:18)
您显示的字符串不是JSON编码的对象(对于Python dict而言是eqv) - 更像是一个没有括号的数组(eqv到列表),并且在末尾有一个逗号额外的逗号。所以(使用simplejson版本可移植性 - 2.6中的标准库json
当然也没问题! - ):
>>> 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'}]
如果你真的想要一个字典,你必须指定如何处理这两个未命名的项目,即你想要拍哪些任意键......?
答案 2 :(得分:2)
django.utils.simplejson.loads(someJson)
答案 3 :(得分:0)
First thing first.
Here I have stored your pulled data string into a variable named data_str which has two dictionaries.
>>> data_str = "{\"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\"},"
After that I converted it into another string named data_str2 which is in list form and removed extra comma(,) from end (as it gives error while string data to python object conversion).
>>> data_str2 = "[" + data_str[0: 1] + data_str[1: len(data_str)-1] + "]"
Finally, I converted this list string (a list having 2 dictionaries) into original python list and stored it in a variable named data_list.
>>> import json
>>> data_list = json.loads(data_str2) # Now data_list is a list having 2 dictionaries
Now let's print our data.
>>> print data_list
[{u'description': u'fdsafsa', u'order': u'1', u'place': u'22 Plainsman Rd, Mississauga, ON, Canada', u'lat': 43.5969175, u'lng': -79.7248744, u'locationDate': u'03/24/2010'}, {u'description': u'sadfdsa', u'order': u'2', u'place': u'50 Dawnridge Trail, Brampton, ON, Canada', u'lat': 43.7304774, u'lng': -79.8055435, u'locationDate': u'03/26/2010'}]
>>>
>>> print type(data_list)
<type 'list'>
>>>
>>> print data_list[0]
{u'description': u'fdsafsa', u'order': u'1', u'place': u'22 Plainsman Rd, Mississauga, ON, Canada', u'lat': 43.5969175, u'lng': -79.7248744, u'locationDate': u'03/24/2010'}
>>>
>>> print data_list[1]
{u'description': u'sadfdsa', u'order': u'2', u'place': u'50 Dawnridge Trail, Brampton, ON, Canada', u'lat': 43.7304774, u'lng': -79.8055435, u'locationDate': u'03/26/2010'}
>>>
Pass this data_list list from views and access it in your Django template as follows,
{% for data in locations %}
<tr>
<td> {{ data.place }} </td>
<td> {{ data.locationDate }} </td>
</tr>
{% endfor %}
A sample code segment for your views.
def locations(request):
# YOU HAVE TO WRITE YOUR CODE LOGIC HERE TO GET THE LIST,
# I AM WRITING IT DIRECTLY
data_list = [{u'description': u'fdsafsa', u'order': u'1', u'place': u'22 Plainsman Rd, Mississauga, ON, Canada', u'lat': 43.5969175, u'lng': -79.7248744, u'locationDate': u'03/24/2010'}, {u'description': u'sadfdsa', u'order': u'2', u'place': u'50 Dawnridge Trail, Brampton, ON, Canada', u'lat': 43.7304774, u'lng': -79.8055435, u'locationDate': u'03/26/2010'}]
return render(request, "locations.html", {"locations": data_list})
IT WORKED NICE.
Now I wanna explain that how I reached to solution, I think it will be helpful for beginners. Please see the below explained step by step procedure or see here.
>>> import json
>>>
>>> # A simple attempt
>>> s = "{\"description\":\"fdsafsa\"}"
>>> python_dict = json.loads(s)
>>> python_dict
{u'description': u'fdsafsa'}
>>> # Accessing value using key
>>> python_dict["description"]
u'fdsafsa'
>>>
>>> # It worked, lets test our given string containing 2 dictionaries(in string form) one by one
>>> # Converting 1st JSON string to Dict
>>> s2 = "{\"description\":\"fdsafsa\",\"order\":\"1\",\"place\":\"22 Plainsman Rd, Mississauga, ON, Canada\",\"lat\":43.5969175,\"lng\":-79.7248744,\"locationDate\":\"03/24/2010\"}"
>>> python_dict2 = json.loads(s2) >>> python_dict2
{u'description': u'fdsafsa', u'order': u'1', u'place': u'22 Plainsman Rd, Mississauga, ON, Canada', u'lat': 43.5969175, u'lng': -79.7248744, u'locationDate': u'03/24/2010'}
>>>
>>> # Converting 2nd JSON string to Dict
>>> # remove comma(,) from end otherwise you will get the following error
>>> s3 = "{\"description\":\"sadfdsa\",\"order\":\"2\",\"place\":\"50 Dawnridge Trail, Brampton, ON, Canada\",\"lat\":43.7304774,\"lng\":-79.8055435,\"locationDate\":\"03/26/2010\"},"
>>> python_dict3 = json.loads(s3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 367, in decode
raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 1 column 152 - line 1 column 153 (char 151 - 152)
>>>
>>> # Now I removed comma(,) from end and retried, it worked
>>> s3 = "{\"description\":\"sadfdsa\",\"order\":\"2\",\"place\":\"50 Dawnridge Trail, Brampton, ON, Canada\",\"lat\":43.7304774,\"lng\":-79.8055435,\"locationDate\":\"03/26/2010\"}"
>>> python_dict3 = json.loads(s3)
>>>
>>> # So now we knew that we have not to include any extra comma at end in the string form of JSON
>>> # For example (Correct form)
>>> details_str = "{\"name\":\"Rishikesh Agrawani\", \"age\": 25}"
>>> details_dict = json.loads(details_str)
>>> details_dict["name"]
u'Rishikesh Agrawani'
>>> details_dict["age"]
25
>>> # Now (Incorrect form), here comma(,) is at end, just after }
>>> details_str = "{\"name\":\"Rishikesh Agrawani\", \"age\": 25},"
>>> details_dict = json.loads(details_str)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 367, in decode
raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 1 column 41 - line 1 column 42 (char 40 - 41)
>>>
>>> # The problem is the string does not denote any single python object
>>> # So we will convert the string into a list form by appending [ at beginning and ] at end
>>> # Now our string will denote a single Pytohn object that is list of 2 dictioanaries
>>> # Lets do this, here I am storing the given string into variable s4
>>> data_str = "{\"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\"},"
>>> s5 = "[" + s4[0:1] + s4[1: len(s4)-1] + "]"
>>> s5
'[{"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"}]'
>>> # l is a list of 2 dictionaries
>>> l = json.loads(s5)
>>> l[0]
{u'description': u'fdsafsa', u'order': u'1', u'place': u'22 Plainsman Rd, Mississauga, ON, Canada', u'lat': 43.5969175, u'lng': -79.7248744, u'locationDate': u'03/24/2010'}
>>>
>>> l[1]
{u'description': u'sadfdsa', u'order': u'2', u'place': u'50 Dawnridge Trail, Brampton, ON, Canada', u'lat': 43.7304774, u'lng': -79.8055435, u'locationDate': u'03/26/2010'}
>>>
Thanks.
答案 4 :(得分:0)
Hello here my example
import json
class SimpleObject(object):
def __init__(self, _dict):
self.__dict__.update(_dict)
data=json.loads("{\"name\":\"Rishikesh Agrawani\", \"age\": 25}" )
so=SimpleObject(data)
print (so.name)
print (so.age)
if you transform your data to objects is better and more fast work.
答案 5 :(得分:0)
只是其他答案的组合:
import json
yourString = "{\"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\"},"
target = json.loads("[" + yourString[:-1] + "]")
输出
[{u'description': u'fdsafsa', u'order': u'1', u'place': u'22 Plainsman Rd, Mississauga, ON, Canada', u'lat': 43.5969175, u'lng': -79.7248744, u'locationDate': u'03/24/2010'}, {u'description': u'sadfdsa', u'order': u'2', u'place': u'50 Dawnridge Trail, Brampton, ON, Canada', u'lat': 43.7304774, u'lng': -79.8055435, u'locationDate': u'03/26/2010'}]
如上所述
[]
),
,通过[:-1]
切片语法删除