简体   繁体   English

将 JSON 转换为 Python dict

[英]Converting JSON into Python dict

I've been searching around trying to find an answer to this question, and I can't seem to track it down.我一直在四处寻找这个问题的答案,但我似乎无法找到它。 Maybe it's too late in the evening to figure the answer out, so I turn to the excellent readers here.可能晚上想出答案已经太晚了,所以我求助于这里的优秀读者。

I have the following bit of JSON data that I am pulling out of a CouchDB record:我从 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\"},"

This data is stored inside a Python dict under the key ' locations ' in a dict called ' my_plan '.该数据存储在名为“ my_plan ”的 dict 中的键“ locations ”下的 Python dict 中。 I want to covert this data from CouchDB into a Python dict so I can do the following in a Django template:我想将此数据从 CouchDB 转换为 Python dict,以便我可以在 Django 模板中执行以下操作:

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

{% endfor %}

I've found lots of info on converting dicts to JSON, but nothing on going back the other way.我发现了很多关于将 dicts 转换为 JSON 的信息,但没有任何其他方式可以返回。

  • Use the json module for loading JSON.使用json模块加载 JSON。 (Pre-2.6 use the third party simplejson module, which has the same exact API.) (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]}
  • Your actual data cannot be loaded this way since it's actually two JSON objects separated by a comma and with a trailing comma.您的实际数据无法以这种方式加载,因为它实际上是由逗号分隔的两个 JSON 对象,并带有一个尾随逗号。 You'll need to separate them or otherwise deal with this.您需要将它们分开或以其他方式处理此问题。

    • Where did you get this string?你从哪里得到这个字符串?

The string you show is not a JSON-coded object (eqv to a Python dict) — more like an array (eqv to a list) without brackets and with a stray extra comma at the end.您显示的字符串不是 JSON 编码的对象(eqv 到 Python dict)——更像是一个数组(eqv 到列表),没有括号,末尾有一个额外的逗号。 So (using simplejson for version portability — the standard library's json in 2.6 is fine too of course!-):所以(使用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'}]

If you really want a dict you'll have to specify how to treat these two unnamed items, ie, what arbitrary keys you want to slap on them...?如果你真的想要一个字典,你必须指定如何处理这两个未命名的项目,即,你想对它们施加什么任意键......?

django.utils.simplejson.loads(someJson)

First thing first .首先

Here I have stored your pulled data string into a variable named data_str which has two dictionaries .在这里,我已将您提取的数据字符串存储到名为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\"},"

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 的字符串,它是列表形式,并从末尾删除了额外的逗号( )(因为它在将字符串数据转换为python 对象时会出错)。

>>> 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 .最后,我将此列表字符串(一个包含 2 个字典的列表)转换为原始python 列表并将其存储在名为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,从视图传递这个data_list列表并在你的Django 模板中访问它,如下所示,

{% 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 orsee 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 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'}
>>>                                                           

Thanks .谢谢

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.

Just a combination of other answers:只是其他答案的组合:

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] + "]")

outputs产出

[{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'}]

As mentioned如上所述

  • this string contains two json objects, so put it inside an array (the [] )这个字符串包含两个 json 对象,所以把它放在一个数组中( []
  • it has a trailing , , remove via [:-1] slicing syntax它有一个尾随, , 通过[:-1]切片语法删除

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM