pandas 如何根据具体值保存json对象变量

trnvg8h3  于 2022-12-25  发布在  其他
关注(0)|答案(3)|浏览(154)

我尝试在python中从url读取json响应。下面的代码工作正常,但问题是我需要根据主题获取密钥,例如,如果主题是“* 每日指数水平 ”,则它应该打印以下密钥hkr1omlsnteodhkvnt98q20682ghv1fmegb8de01

import json, pandas as pd
import urllib

URL = "https://pv-ft-marketdata-store.ihsmvals-dev.com/email/search"
response = urllib.request.urlopen(URL)
text = response.read()
json_data = json.loads(text)
print(json_data)
deyfvvtc

deyfvvtc1#

要从列表中得到符合条件的第一个值,我们可以传递 * generator expression ,它会带条件直接迭代这个列表到next()中,next()会从传递的生成器中返回第一个值。如果有两个或多个值与条件匹配,则需要获取具有 "最近处理时间" 的值我假设它存储在list中每个JSON对象的"processed"键中,并且包含ISO格式的日期。(使用list.sort()"processed"键值的降序排列 (将itemgetter()作为key参数传递) 在查找之前。最后,您 * 提到 * 需要在下一个URL中使用提取的"key",因此您只需将其连接在您提供的两个URL路径部分之间。

    • 代码:**
import json
from urllib.request import urlopen
from operator import itemgetter

with urlopen('https://pv-ft-marketdata-store.ihsmvals-dev.com/email/search') as resp:
    json_data = json.load(resp)
    
json_data.sort(key=itemgetter("processed"), reverse=True)
key = next(d["key"] for d in json_data if d["subject"] == "Indices Daily Level")

URL = "https://pv-ft-marketdata-store.ihsmvals-dev.com/email/" + key + "/data/html"
print(URL)
xvw2m8pv

xvw2m8pv2#

print(next(d["key"] for d in json_data if d["subject"] == "Indices Daily Level"))
key = str(next(d["key"] for d in json_data if d["subject"] == "Indices Daily Level"))

URL = "https://pv-ft-marketdata-store.ihsmvals-dev.com/email/" + 'key'  "/data/html"
print(URL)
yhxst69z

yhxst69z3#

import json
from urllib.request import urlopen
from operator import itemgetter
import pandas as pd
import requests
import re

with urlopen('https://pv-ft-marketdata-store.ihsmvals-dev.com/email/search') as resp:
    json_data = json.load(resp)

json_data.sort(key=itemgetter("processed"), reverse=True)
key = next(d["key"] for d in json_data
if d["subject"].startswith ("Morgan Stanley Systematic Strategies Daily Levels")

URL = "https://pv-ft-marketdata-store.ihsmvals-dev.com/email/" + key + "/data/html"
html = requests.get(URL).content
df_list = pd.read_html(html)
df = df_list[-1]
print(df)

相关问题