簡體   English   中英

將 JSON 轉換為 Python dict

[英]Converting JSON into Python dict

我一直在四處尋找這個問題的答案,但我似乎無法找到它。 可能晚上想出答案已經太晚了,所以我求助於這里的優秀讀者。

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

該數據存儲在名為“ my_plan ”的 dict 中的鍵“ locations ”下的 Python dict 中。 我想將此數據從 CouchDB 轉換為 Python dict,以便我可以在 Django 模板中執行以下操作:

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

{% endfor %}

我發現了很多關於將 dicts 轉換為 JSON 的信息,但沒有任何其他方式可以返回。

  • 使用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 對象,並帶有一個尾隨逗號。 您需要將它們分開或以其他方式處理此問題。

    • 你從哪里得到這個字符串?

您顯示的字符串不是 JSON 編碼的對象(eqv 到 Python dict)——更像是一個數組(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'}]

如果你真的想要一個字典,你必須指定如何處理這兩個未命名的項目,即,你想對它們施加什么任意鍵......?

django.utils.simplejson.loads(someJson)

首先

在這里,我已將您提取的數據字符串存儲到名為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 的字符串,它是列表形式,並從末尾刪除了額外的逗號( )(因為它在將字符串數據轉換為python 對象時會出錯)。

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

效果很好。

現在我想解釋一下我是如何找到解決方案的,我認為這對初學者會有所幫助。 請參閱下面解釋的分步程序或參閱此處

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

謝謝

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.

只是其他答案的組合:

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]切片語法刪除

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM