尝试使用pandas将json转换为csv时,将dicts与nonseries混合出现错误,但仅当从url检索到json时发生错误

2024-10-01 07:13:06 发布

您现在位置:Python中文网/ 问答频道 /正文

Python 3.8.5和Pandas 1.1.3

使用pandas将Python json dict list转换为csv的代码可以正常工作:

import csv
import pandas as pd
import json

data = [{"results": [{"type": "ID", "value": "1234", "normalized": "1234", "count": 1, "offsets": [{"start": 14, "end": 25}], "id_b": "10"}, {"type": "ID", "value": "5678", "normalized": "5678", "count": 1, "offsets": [{"start": 32, "end": 43}], "id_b": "11"}], "responseHeaders": {"Date": "Tue, 25 May 2021 14:41:28 GMT", "Content-Type": "application/json", "Content-Length": "350", "Connection": "keep-alive", "Server": "openresty", "X-StuffAPI-ProcessedLanguage": "eng", "X-StuffAPI-Request-Id": "abcdef", "Strict-Transport-Security": "max-age=63072000; includeSubDomains; preload", "X-StuffAPI-App-Id": "123456789", "X-StuffAPI-Concurrency": "1"}}]

pd.read_json(json.dumps(data)).to_csv('file.csv')

上面的data变量中的值直接从对我们的一个服务的API调用响应粘贴。当我尝试在一个脚本中执行包括API调用在内的所有操作时,就会出现问题。让我们首先看一下脚本中似乎工作正常的所有内容:

    import csv
    import pandas as pd
    import json
    import stuff.api
    
    def run(key, url):
        # Create an API instance
        api = API(user_key=key, service_url=url)
        # submit data from a text file to the API parser
        file1 = open("123.txt","r")
            text_data = file1.read()
            params = DocumentParameters()
            params["content"] = text_data
            file1.close()
            try:
                return api.data(params)
            except StuffAPIException as exception:
                print(exception)
    
    if __name__ == '__main__':
    
        result = run('1234', 'https://192.168.0.125:8100/rest/')
        y = json.dumps(result)
        t = type(y)
        print(y)
        print(t)

上面的print(y)语句将返回我在上面第一个代码块的data变量中显示的确切数据。而print(t)语句用于捕获返回类型,以帮助我尝试并诊断问题-结果是<class 'str'>

现在,我们在print(t)行下面添加这个代码(与第一个代码块完全相同):

pd.read_json(json.dumps(result)).to_csv('file.csv')

我得到了这个错误:

ValueError: Mixing dicts with non-Series may lead to ambiguous ordering.

我已经看到了很多关于这个错误的线索,但是没有一条与这里发生的事情完全相关

以我目前有限的经验,我猜这个问题可能是由于返回类型为string?我不确定,但这一故障排除步骤只是要克服的第一个障碍-我需要最终能够将数据解析到csv文件的单独列中,但现在,我只需要将其无错误地放入csv文件中

我知道如果不访问我的服务器,您将无法完全复制此内容,但希望您不需要这样做来解决此问题


Tags: csvto代码importapijsonpandasread