如何在Django中将Http Post参数的Json值转换为Python Dict?

时间:2011-09-20 03:50:12

标签: python django json api foursquare

我正在使用Django从foursquare实时api接收和处理推送通知。每个签入都作为POST请求推送到包含名为checkin的单个参数的服务器。我试图获取checkin参数的值并将其转换为python dict。但是,调用json.loads总是会导致以下错误:

NameError: name 'true' is not defined

我知道json是有效的,所以我一定做错了。

代码是:

import json    
def push(request):
  if request.is_secure():
    checkin_json = request.POST['checkin']
    checkin = json.load(request.POST)

发布请求的正文是:

"checkin = 
{
"id": "4e6fe1404b90c00032eeac34",
"createdAt": 1315955008,
"type": "checkin",
"timeZone": "America/New_York",
"user": {
    "id": "1",
    "firstName": "Jimmy",
    "lastName": "Foursquare",
    "photo": "https://foursquare.com/img/blank_boy.png",
    "gender": "male",
    "homeCity": "New York, NY",
    "relationship": "self"
},
"venue": {
    "id": "4ab7e57cf964a5205f7b20e3",
    "name": "foursquare HQ",
    "contact": {
        "twitter": "foursquare"
    },
    "location": {
        "address": "East Village",
        "lat": 40.72809214560253,
        "lng": -73.99112284183502,
        "city": "New York",
        "state": "NY",
        "postalCode": "10003",
        "country": "USA"
    },
    "categories": [
        {
            "id": "4bf58dd8d48988d125941735",
            "name": "Tech Startup",
            "pluralName": "Tech Startups",
            "shortName": "Tech Startup",
            "icon": "https://foursquare.com/img/categories/building/default.png",
            "parents": [
                "Professional & Other Places",
                "Offices"
            ],
            "primary": true
        }
    ],
    "verified": true,
    "stats": {
        "checkinsCount": 7313,
        "usersCount": 565,
        "tipCount": 128
    },
    "url": "http://foursquare.com"
}
}"

3 个答案:

答案 0 :(得分:4)

尝试使用json.loads(checkin_json)代替json.load(request.POST)。注意额外的's'。

答案 1 :(得分:0)

checkin = json.load(request.POST)更改为checkin = json.loads(checkin_json)

答案 2 :(得分:-1)

在python上,布尔值为大写(第一个字母为大写):True / False。

检查一下。

编辑: 请注意以下几点:

"primary": true
    }
],
"verified": true,

两个“true”值都是小写的,需要大写