Khung dữ liệu từ API sang CSV

Sep 03 2020

Tôi đang ở python và cố gắng xuất dữ liệu từ API sang csv

import requests
import pandas as pd


url = "https://api.bexio.com/2.0/article"
#r = requests.get('https://api.bexio.com/2.0/article')
headers = {
'Accept': "application/json",
'Content-Type': "application/json",
'Authorization': "Bearer xxx}

Điều đó hoạt động tốt.

  [{"id":34,"user_id":1,"article_type_id":1,"contact_id":null,"deliverer_code":"","deliverer_name":"","deliverer_description":"","intern_code":"TEXLINE-SOLD","intern_name":"TEXLINE Sold out","intern_description":"","purchase_price":"0.900000","sale_price":"2.450000","purchase_total":null,"sale_total":null,"currency_id":1,"tax_income_id":16,"tax_id":16,"tax_expense_id":22,"unit_id":1,"is_stock":true,"stock_id":null,"stock_place_id":null,"stock_nr":0,"stock_min_nr":0,"stock_reserved_nr":0,"stock_available_nr":0,"stock_picked_nr":0,"stock_disposed_nr":0,"stock_ordered_nr":0,"width":null,"height":null,"weight":null,"volume":null,"html_text":null,"remarks":"

vấn đề ở đây là, tôi muốn xuất dữ liệu này sang csv nơi sau đó được liệt kê độc đáo trong một bảng. Tôi đã thử với

from pandas.io.json import json_normalize
dic = response.json()
df = pandas.DataFrame(dic)
df.to_csv('detections.csv', index=False, sep="\t")

hoặc với gấu trúc là pd. Nhưng điều đó không hiệu quả.

Trả lời

2 perl Sep 03 2020 at 12:16

Hãy thử với read_jsonnếu bạn có JSON của mình dưới dạng chuỗi:

df = pd.read_json(json_string)

Hoặc, cách khác, chuyển đổi phản hồi API thành danh sách python .json()và trực tiếp tạo một DataFrametừ danh sách đó:

r = requests.get('https://jsonplaceholder.typicode.com/posts')
df = pd.DataFrame(r.json())

Nếu phản hồi không phải là một list ( [{..}, .., {..}]) mà là một đối tượng ( {..}):

r = requests.get('https://jsonplaceholder.typicode.com/posts/1')
df = pd.DataFrame(r.json(), index=[0])