Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

django - 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:

"{"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'. I want to covert this data from CouchDB into a Python dict so I can do the following in a Django template:

{% 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • Use the json module for loading JSON. (Pre-2.6 use the third party simplejson module, which has the same exact 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. You'll need to separate them or otherwise deal with this.

    • Where did you get this string?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...