2010-03-21 104 views
23

我一直在四处搜寻试图找到这个问题的答案,我似乎无法跟踪它。也许现在晚上想出答案已经太晚了,所以我转向这里的优秀读者。将JSON转换为Python字典

我有我拉出的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字典,所以我可以做Django模板如下:

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

{% endfor %} 

我发现大量的信息在类型的字典转换成JSON,但在回去的其他任何办法。

回答

18

告诉你的字符串不是一个JSON编码的对象(当量于Python字典) - 更像是一个数组(当量于列表)没有括号,并在最后一个流浪多余的逗号。所以,(使用simplejson便携版本 - 标准库的json 2.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'}] 

如果你真的想你就会有一个字典,以指定如何看待这两个无名的项目,即你想要击打什么任意键......?

+1

您的解决方案非常完美。谢谢!我将修复在进入CouchDB之前生成数据的例程,以避免附加额外的逗号。深夜编码sloppiness – GrumpyCanuck 2010-03-21 03:48:05

+1

@Grumpy,当然 - 如果我是你,我还会将括号放在数据库中的字符串中,以确保它是有效的JSON,而不是“有点不完整的JSON”接收代码必须完成。 – 2010-03-21 04:01:41

+1

我之前就是这么做的,但是不记得为什么我*停止了*这样做......深夜编码需要从现在开始记录我认为 – GrumpyCanuck 2010-03-22 20:50:53

2
django.utils.simplejson.loads(someJson) 
+1

删除不转换为一个字典。我试过;) – GrumpyCanuck 2010-03-21 03:44:17

+0

它给出的实际错误是“额外的数据:第1行151列-1第304列(字符151 - 304)” – GrumpyCanuck 2010-03-21 03:45:29

+1

然后你没有JSON。 – 2010-03-21 03:45:47

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对象的实际数据无法加载这种方式。你需要将它们分开或以其他方式处理。

    • 你从哪里得到这个字符串?
+0

该字符串来自我正在处理的应用程序生成的数据,为计划旅行,酒吧抓取等的人定制的最新社交应用程序 – GrumpyCanuck 2010-03-21 03:56:37

0

首先事情第一

这里,我已经存储在您的拉数据串到一个名为data_str其中有两个词典变量。

>>> 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\"}," 

之后,我将它转换到名为data_str2这在列表从端形式并除去额外的逗号()(因为它给出了错误而字符串数据蟒另一个字符串对象转换)。

>>> data_str2 = "[" + data_str[0: 1] + data_str[1: len(data_str)-1] + "]" 

最后,我转换这个列表字符串(具有2名辞典的列表)为原始Python列表并将其存储于命名为DATA_LIST变量。

>>> import json 
>>> data_list = json.loads(data_str2) # Now data_list is a list having 2 dictionaries 

现在让我们打印我们的数据。

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

通行证如下这个DATA_LIST从视图和访问它在您Django的模板名单,

{% for data in locations %} 
     <tr> 
      <td> {{ data.place }} </td> 
      <td> {{ data.locationDate }} </td> 
     </tr> 
{% endfor %} 

一个示例代码段为您的意见。

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。

现在我想解释我不知道怎么达到解决方案,我认为这将是对初学者很有帮助。请参阅以下解释步骤程序或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'} 
>>>               

谢谢

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

如前所述

  • 此字符串包含两个JSON对象,所以把它的阵列内部([]
  • 它具有后,,通过[:-1]切片语法