2010-03-21 219 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]切片語法