【问题标题】:How to Convert Json Value of Http Post Parameter to Python Dict in Django?如何在 Django 中将 Http Post 参数的 Json 值转换为 Python 字典?
【发布时间】:2011-11-20 17:59:55
【问题描述】:

我正在使用 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)

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

【问题讨论】:

    标签: python django json api foursquare


    【解决方案1】:

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

    检查一下。

    编辑: 请注意这一行:

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

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

    【讨论】:

      【解决方案2】:

      尝试json.loads(checkin_json) 而不是json.load(request.POST)。注意多余的“s”。

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 2016-10-20
          • 2021-08-01
          • 2019-04-19
          • 2021-01-17
          • 1970-01-01
          • 2017-11-08
          • 2013-02-14
          • 2023-03-14
          • 1970-01-01
          相关资源
          最近更新 更多