从 Php 文件访问 Json 数据时出错
Error when access Json Data from Php file
我有一个 Json 数据,我可以从我自己的 api
访问
但是 Json 数据不在 .json 文件中,它在 Php 文件中(如下面的 link)
现在我想使用 Python 打印数据
import json
from urllib.request import urlopen
with urlopen("https://**********.000webhostapp.com/api/value/read_all.php") as response:
source = response.read()
data = source
for item in data['value']['temp']:
print(item)
这是我使用的 python 脚本
这是主要错误:
for item in data['value']['temp']:
TypeError: byte indices must be integers or slices, not str
JSON 看起来像:
{"value":[{"id":"1","temp":"25.60","water":"80%","total":"5L","percent":"50%"}...
您需要使用 json.loads()
将 JSON 字符串转换为 Python 字典或列表。使用 decode()
方法将字节转换为字符串。
data = json.loads(source.decode('utf-8'))
您还错误地访问了 JSON。 data['value']
是字典列表,而不是字典本身。循环应该是:
for value in data['value']:
print(value['temp'])
您正在使用 urlopen
从网页读取数据,该网页将 return 一个 response
对象。您可以调用 response.read()
,这将 return 一个字节串。这只是您的网站发送的字节序列。
由于您假设这些字节是有效的 JSON,您将能够将它们解码为字符串,您可以使用 bytes.decode
方法来完成。假设您使用的是 UTF-8 字符集,这将是 bytes.decode('utf-8')
要将 JSON 格式的字符串作为字典加载,您可以使用内置的 json
模块,我看到您已在代码顶部导入了该模块。
放在一起看起来像:
import json
from urllib.request import urlopen
with urlopen("https://**********.000webhostapp.com/api/value/read_all.php") as response:
source = response.read()
my_string = source.decode('utf-8')
my_dictionary = json.loads(my_string)
for item in my_dictionary['value']['temp']:
print(item)
我有一个 Json 数据,我可以从我自己的 api
访问但是 Json 数据不在 .json 文件中,它在 Php 文件中(如下面的 link)
现在我想使用 Python 打印数据
import json
from urllib.request import urlopen
with urlopen("https://**********.000webhostapp.com/api/value/read_all.php") as response:
source = response.read()
data = source
for item in data['value']['temp']:
print(item)
这是我使用的 python 脚本
这是主要错误:
for item in data['value']['temp']:
TypeError: byte indices must be integers or slices, not str
JSON 看起来像:
{"value":[{"id":"1","temp":"25.60","water":"80%","total":"5L","percent":"50%"}...
您需要使用 json.loads()
将 JSON 字符串转换为 Python 字典或列表。使用 decode()
方法将字节转换为字符串。
data = json.loads(source.decode('utf-8'))
您还错误地访问了 JSON。 data['value']
是字典列表,而不是字典本身。循环应该是:
for value in data['value']:
print(value['temp'])
您正在使用 urlopen
从网页读取数据,该网页将 return 一个 response
对象。您可以调用 response.read()
,这将 return 一个字节串。这只是您的网站发送的字节序列。
由于您假设这些字节是有效的 JSON,您将能够将它们解码为字符串,您可以使用 bytes.decode
方法来完成。假设您使用的是 UTF-8 字符集,这将是 bytes.decode('utf-8')
要将 JSON 格式的字符串作为字典加载,您可以使用内置的 json
模块,我看到您已在代码顶部导入了该模块。
放在一起看起来像:
import json
from urllib.request import urlopen
with urlopen("https://**********.000webhostapp.com/api/value/read_all.php") as response:
source = response.read()
my_string = source.decode('utf-8')
my_dictionary = json.loads(my_string)
for item in my_dictionary['value']['temp']:
print(item)