Python:如何获得介于字符串的两个已知部分之间的字符串的一部分?

时间:2018-12-16 14:01:24

标签: python-3.x

这里是我的代码:

import requests
import json

import requests

url =("http://yugiohprices.com/api/get_card_prices/Armed Dragon LV5")

resp = requests.get(url=url)
data = resp.json() # Check the JSON Response Content documentation below
json_string = json.dumps(data)
print(json_string)
print("---------------------")

运行此命令可以给我:

{"status": "success", "data": [{"name": "Legendary Duelists: Ancient Millennium", "print_tag": "LED2-EN026", "rarity": "Common", "price_data":

我想专门讲一下“传奇决斗者:远古千年”。

使用

json_string.split("name")[1]

将其记入

": "Legendary Duelists: Ancient Millennium", "print_tag": "LED2-EN026", "rarity": "Common", "price_data": {

但是我如何摆脱其余的东西?

1 个答案:

答案 0 :(得分:2)

resp = requests.get(url=url)
data = resp.json() # Check the JSON Response Content documentation below
json_string = json.dumps(data)

此代码的作用:从url获取响应,转换为字典,然后将其转换回字符串。

您已经拥有一个字典,它比字符串更容易使用。另外,不能保证服务器将始终以相同的顺序返回响应(这显然会破坏将响应解析为字符串的任何尝试。)

通过键访问所需的数据:

import requests
import json

url = ("http://yugiohprices.com/api/get_card_prices/Armed Dragon LV5")

resp = requests.get(url=url)
response_json = resp.json()

print(response_json['data'][0]['name'])
# Legendary Duelists: Ancient Millennium

如果要获取所有名称,请使用循环:

for data in response_json['data']:
    print(data['name'])

将输出

Legendary Duelists: Ancient Millennium
Structure Deck: Dragon's Roar
Duelist Pack: Chazz Princeton
Legendary Collection 3: Yugi's World Mega Pack
Dark Revelation Volume 3
Soul of the Duelist
Dragunity Legion Structure Deck
Soul of the Duelist