json - 从熊猫数据框创建一个json并发布到rest api
问题描述
我需要将数据发送到接受这种格式的 REST API
{'myattributes':
[{'a': {},
'v': {},
'c': {},
'd': {},
'e': {},
'f': {},
'g': {},
'h': {}}]}
我正在从数据框中读取文件,如何将数据框映射到所需的 json 格式?
url = 'https://cyz.com/hello
response = requests.post(url, json=s, headers=head)
print(response)
print(response.json())
解决方案
import pandas as pd
# grabbing a sample file to demonstrate
df = pd.read_csv("https://www1.ncdc.noaa.gov/pub/data/cdo/samples/PRECIP_HLY_sample_csv.csv")
print(df) # what it looks on read
# if the column names don’t match what’s needed for the api post json,rename them
df = df.rename(columns={'STATION':'a','STATION_NAME':'b',
'ELEVATION':'c','LATITUDE':'d',
'LONGITUDE':'e','DATE':'f','HPCP':'g',
'Measurement Flag':'h','Quality Flag':'i'})
print(df) # what it looks like after the rename
# render a list of 'json' posts from the dataframe
posts = json.loads('{"items":' + df.to_json(orient='records', date_format='iso') + '}')
print(posts['items']) # see the results
# since posts['items'] is a list, the set of posts can be executed using list comprehension like line below
# [requests.post('http://someurl.com/path', json=post, headers={'Accept':'application/json'}) for post in posts['items'] ```
推荐阅读
- android - 如何禁用recyclerview的内部滚动但保持外部列表滚动?(如材料设计指南中所示)
- julia - 范围之间的条件子集数组
- algorithm - 整数线性规划 (ILP) 的运行时间复杂度是多少?
- c# - 禁用在 Windows 10 上的文本框焦点上自动打开触摸键盘 (TabTip.exe),2018 年 4 月更新
- latex - Latex:\printglossaries 在 Mac 上不起作用?
- ruby-on-rails - 允许用户使用 Doorkeeper 撤销令牌
- json - 使用 jslt 转换 json 以包含空格字符
- java - ElasticsearchStatusException[Elasticsearch 异常 [type=search_phase_execution_exception, reason=all shards failed]]
- php - 如何将现有应用程序与 Joomla 集成?
- c# - PowerShell 导致 C# 应用程序因异常而终止