python - 在 Python 中访问嵌套 JSON 数据

标签 python json

我的程序有一个 JSON 类,我需要访问其中的某些项目。

我不太明白它是什么类型的数据结构,这可能是我的问题的一部分。

我尝试过 json.dumps()json.load(),两者都返回错误。我什至尝试过._dict_

我收到以下错误:
“JSON 对象必须是 str、bytes 或 bytearray,而不是‘LambdaContext’”、“‘LambdaContext’对象没有属性‘_dict_’”和“‘LambdaContext’类型的对象不可 JSON 序列化。”我不知道还能用这个 JSON 数据做什么。

我需要访问“apiAccessToken”。

JSON 数据:

{
  "context": {
    "System": {
      "apiAccessToken": "AxThk...",
      "apiEndpoint": "https://api.amazonalexa.com",
      "device": {
        "deviceId": "string-identifying-the-device",
        "supportedInterfaces": {}
      },
      "application": {
        "applicationId": "string"
      },
      "user": {}
    }
  }
}

我的代码:

def postalCodeRetriever(intent, session, context):
    deviceId = session['user']['userId']
    jsoninfo = json.dumps(context)
    json_dict = json.loads(jsoninfo)
    print(str(json_dict))
    TOKEN = context["System"]
    print(TOKEN)
    URL = "https://api.amazonalexa.com/v1/devices/" + deviceId + "/settings/address/countryAndPostalCode"
    HEADER = {'Accept': 'application/json', 'Authorization': 'Bearer ' + TOKEN}
    response = urllib2.urlopen(URL, headers=HEADER)
    data = json.load(response)
    postalCode = data['postalCode']
    return build_response({}, build_speechlet_response(
                "hello", postalCode, None, True))

最佳答案

下面的代码应该可以做到这一点:

import json
data = json.dumps({
  "context": {
    "System": {
      "apiAccessToken": "AxThk...",
      "apiEndpoint": "https://api.amazonalexa.com",
      "device": {
        "deviceId": "string-identifying-the-device",
        "supportedInterfaces": {}
      },
      "application": {
        "applicationId": "string"
      },
      "user": {}
    }
  }
})
data_dict = json.loads(data)
print(data_dict['context']['System']['apiAccessToken'])

输出:

AxThk...

关于python - 在 Python 中访问嵌套 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48002339/

相关文章:

python - 如何使用 json.loads 将字符串 int JSON 转换为真正的 int

php - json mysql 数据到 d3 绘图

php - 使用 Laravel 4 生成 RESTful 响应

python - arg解析错误: 'nargs must be %r to supply const' % OPTIONAL)

python - tkinter 自动完成小部件小写偏差

python向导入的模块添加变量

python - 使顶级窗口跟随根 Tk 窗口

mysql - 查找 MySQL JSON 对象或数组的交集

java - 使用 Java 检查一个值是否存在于 JSON 对象中

python - Pandas 拆单列