繁体   English   中英

从python中的json数组访问数据

[英]Accessing data from a json array in python

我的回应之一是,

{
    "password": [
        "Ensure that this field has atleast 5 and atmost 50 characters"
    ]
}

我正在尝试获取密码中的字符串。如何获取它。

下面是我正在尝试的代码

key = json.loads(response['password'])
print(key[0]),

但它说“字符串索引必须是整数,而不是str”

错误消息是正确的。

key = json.loads(response['password'])
print(key[0]),

json的格式是字符串。 您需要先将json对象的字符串转换为python dict,然后才能访问它。

即:在info[key]之前loads(string)

key = json.loads(response)['password']
print(key[0])

通常json是一个字符串,您将尝试将其反序列化为对象图(在python中通常由映射和数组组成)。

因此,假设您的响应实际上是一个字符串(例如,从HTTP请求/端点检索到的字符串),则可以使用json.loads(该函数基本上是从字符串加载)来反序列化它,那么您将获得一个带有“密码”的映射键,它是一个数组,因此请从中获取第一个元素。

import json

resp = '{ "password": [ "Ensure that this field has atleast 5 and atmost 50 characters" ] }'
print json.loads(resp)['password'][0]

暂无
暂无

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

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