使用 Python 从 JSON 响应中取出 1 个特定项目
Taking 1 specific item out of JSON response using Python
我正在尝试获取 "id" 号码,然后在程序中使用它。如果重要的话,响应是 .json
{"run_at":1818086502,"quantity":295092,"queue":"units","original_duration":388900193,"duration":388900193,"unit_type":"Harrier","city_id":1102142875,"id":3720348749},"success":true}}
这是 "id" 所在的响应的一部分。
这是我目前所拥有的:
cadena= "Draoumculiasis" + params + "LandCrocodile" + url + "Bevar-Asp"
cadenau=cadena.encode('utf8')
m=hashlib.sha1(cadenau)
xs3=m.hexdigest()
headers= { 'Host': realm , 'Connection': 'keep-alive', 'Content-Length': len(params), 'Origin': 'http://castlemania-production.s3.amazonaws.com', 'x-s3-aws': xs3, 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.79 Safari/535.11', 'content-type': 'application/x-www-form-urlencoded', 'Accept': '*/*', 'Accept-Encoding': 'gzip,deflate,sdch', 'Accept-Language': 'es-ES,es;q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'DNT': 1, 'Cookie': cookie }
conn=http.client.HTTPConnection(realm,80)
conn.request("POST",url,params, headers)
response=conn.getresponse()
Id 每次都改变。
我已经制作了制作 id 和使用 id 的部分,我需要连接这两个而不需要手动输入。
遗憾的是我不是程序员,所以我正在寻找可能的完整解决方案。我做了一些研究,但无法弄清楚。
更新 1
按照 Gord 的回答中的建议,我使用
responseData = response.read().decode('utf-8')
items = json.loads(responseData)
现在我得到了错误
Traceback (most recent call last):
File "N:\Files\doa\Py's\testinggettingid.py", line 54, in <module>
items = json.loads(responseData)
File "C:\Python34\lib\json\__init__.py", line 318, in loads
return _default_decoder.decode(s)
File "C:\Python34\lib\json\decoder.py", line 343, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python34\lib\json\decoder.py", line 361, in raw_decode
raise ValueError(errmsg("Expecting value", s, err.value)) from None
ValueError: Expecting value: line1 column 1 (char 0)
更新2
我已通过
删除了错误
response=conn.getresponse()
responseData = response.read().decode('utf-8')
print(responseData)
items = json.loads(responseData)
idValue = items['id']
print(idValue)
但它显示的是我的玩家 ID 而不是工作 ID。
更新 3
打印(response.getheaders()) 根据要求
如果我没理解错的话,您有一个 JSON 响应,并且您想要提取名为 "id" 的字段的值。从您的问题看来,您不熟悉 JSON 语法。遇到这种情况请咨询W3schools' JSON syntax manual and/or the documentation for Python's JSON library
import json
response = json.loads("{\"msg\": {\"run_at\":1818086502,\"quantity\":295092,\"queue\":\"units\",\"original_duration\":388900193,\"duration\":388900193,\"unit_type\":\"Harrier\",\"city_id\":1102142875,\"id\":3720348749},\"success\": true}")
print response["msg"]["id"]
以上代码打印对象"msg"中字段"id"的值。
考虑一个简化的示例,其中您的代码行
>>> response=conn.getresponse()
已从服务器检索响应并将其保存为 HTTPResponse object,当您 .read()
响应时,您会看到 JSON 字符串,如下所示
>>> responseData = response.read().decode('utf-8')
>>> responseData
'{"day": "Thursday", "id": 3720348749}'
您可以使用 Python 的内置 JSON 解码器将其转换为名为 items
的字典对象
>>> import json
>>> items = json.loads(responseData)
现在您可以通过引用关键字为'id'
的词典条目来提取id
值
>>> idValue = items['id']
>>> print(idValue)
3720348749
如果你明天运行相同的代码并且返回的response
对象包含
>>> responseData = response.read().decode('utf-8')
>>> responseData
'{"day": "Friday", "id": 4567890123}'
然后同一组步骤将为 id
提取新值
>>> import json
>>> items = json.loads(responseData)
>>> idValue = items['id']
>>> print(idValue)
4567890123
更新
如果您的实际 JSON 数据包含嵌套元素,那么您可能需要使用多个 "key" 值来标识您想要的项目。例如,如果您要检索的 "id" 实际上是
result
job
id
即 JSON 看起来像
'{"result": {"job": {"id": 12345678}}}'
那么你将需要使用
idValue = items['result']['job']['id']
我正在尝试获取 "id" 号码,然后在程序中使用它。如果重要的话,响应是 .json
{"run_at":1818086502,"quantity":295092,"queue":"units","original_duration":388900193,"duration":388900193,"unit_type":"Harrier","city_id":1102142875,"id":3720348749},"success":true}}
这是 "id" 所在的响应的一部分。
这是我目前所拥有的:
cadena= "Draoumculiasis" + params + "LandCrocodile" + url + "Bevar-Asp"
cadenau=cadena.encode('utf8')
m=hashlib.sha1(cadenau)
xs3=m.hexdigest()
headers= { 'Host': realm , 'Connection': 'keep-alive', 'Content-Length': len(params), 'Origin': 'http://castlemania-production.s3.amazonaws.com', 'x-s3-aws': xs3, 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.79 Safari/535.11', 'content-type': 'application/x-www-form-urlencoded', 'Accept': '*/*', 'Accept-Encoding': 'gzip,deflate,sdch', 'Accept-Language': 'es-ES,es;q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'DNT': 1, 'Cookie': cookie }
conn=http.client.HTTPConnection(realm,80)
conn.request("POST",url,params, headers)
response=conn.getresponse()
Id 每次都改变。
我已经制作了制作 id 和使用 id 的部分,我需要连接这两个而不需要手动输入。 遗憾的是我不是程序员,所以我正在寻找可能的完整解决方案。我做了一些研究,但无法弄清楚。
更新 1
按照 Gord 的回答中的建议,我使用
responseData = response.read().decode('utf-8')
items = json.loads(responseData)
现在我得到了错误
Traceback (most recent call last):
File "N:\Files\doa\Py's\testinggettingid.py", line 54, in <module>
items = json.loads(responseData)
File "C:\Python34\lib\json\__init__.py", line 318, in loads
return _default_decoder.decode(s)
File "C:\Python34\lib\json\decoder.py", line 343, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python34\lib\json\decoder.py", line 361, in raw_decode
raise ValueError(errmsg("Expecting value", s, err.value)) from None
ValueError: Expecting value: line1 column 1 (char 0)
更新2 我已通过
删除了错误 response=conn.getresponse()
responseData = response.read().decode('utf-8')
print(responseData)
items = json.loads(responseData)
idValue = items['id']
print(idValue)
但它显示的是我的玩家 ID 而不是工作 ID。
更新 3
打印(response.getheaders()) 根据要求
如果我没理解错的话,您有一个 JSON 响应,并且您想要提取名为 "id" 的字段的值。从您的问题看来,您不熟悉 JSON 语法。遇到这种情况请咨询W3schools' JSON syntax manual and/or the documentation for Python's JSON library
import json
response = json.loads("{\"msg\": {\"run_at\":1818086502,\"quantity\":295092,\"queue\":\"units\",\"original_duration\":388900193,\"duration\":388900193,\"unit_type\":\"Harrier\",\"city_id\":1102142875,\"id\":3720348749},\"success\": true}")
print response["msg"]["id"]
以上代码打印对象"msg"中字段"id"的值。
考虑一个简化的示例,其中您的代码行
>>> response=conn.getresponse()
已从服务器检索响应并将其保存为 HTTPResponse object,当您 .read()
响应时,您会看到 JSON 字符串,如下所示
>>> responseData = response.read().decode('utf-8')
>>> responseData
'{"day": "Thursday", "id": 3720348749}'
您可以使用 Python 的内置 JSON 解码器将其转换为名为 items
>>> import json
>>> items = json.loads(responseData)
现在您可以通过引用关键字为'id'
的词典条目来提取id
值
>>> idValue = items['id']
>>> print(idValue)
3720348749
如果你明天运行相同的代码并且返回的response
对象包含
>>> responseData = response.read().decode('utf-8')
>>> responseData
'{"day": "Friday", "id": 4567890123}'
然后同一组步骤将为 id
>>> import json
>>> items = json.loads(responseData)
>>> idValue = items['id']
>>> print(idValue)
4567890123
更新
如果您的实际 JSON 数据包含嵌套元素,那么您可能需要使用多个 "key" 值来标识您想要的项目。例如,如果您要检索的 "id" 实际上是
result
job
id
即 JSON 看起来像
'{"result": {"job": {"id": 12345678}}}'
那么你将需要使用
idValue = items['result']['job']['id']