简体   繁体   English

如何将 json output 写入 python 中的 csv 文件?

[英]How to write json output to a csv file in python?

I would write in a CSV the JSON output I have from an http request but I'm having this error:我会写在 CSV JSON output 我有来自 Z80791B3AE70029FACB88C24688 请求但 IF76

TypeError: the JSON object must be str, bytes or bytearray, not list

here the snap of my code:这是我的代码的快照:


my_json = json.loads(resp_obj)

    with open("wiki.txt", "a") as myfile:

            writer = csv.writer(myfile)

            for item in my_json["mainsnak"]["datavalue"]:

                    writer.writerow([item, "https://www.geonames.org/{}".format(item["value"])])  #Write row.

    myfile.close()

I tried with this but I still have the error.我试过这个,但我仍然有错误。

Here the resulting JSON from the request:这里是来自请求的 JSON :


[
    {
        "id": "Q6761$59FB3973-0123-4EB4-9C98-F7FEB6AAA32B",
        "mainsnak": {
            "datatype": "external-id",
            "datavalue": {
                "type": "string",
                "value": "6540122"
            },
            "hash": "e7602dcd11d9a83e46716925865bca8e36a9b12c",
            "property": "P1566",
            "snaktype": "value"
        },
        "rank": "normal",
        "references": [
            {
                "hash": "88694a0f4d1486770c269f7db16a1982f74da69d",
                "snaks": {
                    "P248": [
                        {
                            "datatype": "wikibase-item",
                            "datavalue": {
                                "type": "wikibase-entityid",
                                "value": {
                                    "entity-type": "item",
                                    "id": "Q830106",
                                    "numeric-id": 830106
                                }
                            },
                            "hash": "1b3ef912a2bd61e18dd43abd184337eb010b2e96",
                            "property": "P248",
                            "snaktype": "value"
                        }
                    ]
                },
                "snaks-order": [
                    "P248"
                ]
            }
        ],
        "type": "statement"
    }
]

In the CSV file I would parse just "value": "6540122"在 CSV 文件中,我将只解析"value": "6540122"

The TypeError is telling you what the problem is. TypeError告诉您问题所在。 You are trying to pass a list to a function when it expects bytes or a string.当它需要字节或字符串时,您试图将列表传递给 function。 It's hard to say which because you didn't include the part of your error message with that information, but here's my best guess based on the structure of your data:很难说是哪个,因为您没有将错误消息的部分包含在该信息中,但这是我根据您的数据结构做出的最佳猜测:

my_json = json.loads(resp_obj)
with open("wiki.txt", "a") as myfile:
    writer = csv.writer(myfile)
    for item in my_json:
        writer.writerow([item["mainsnak"]["datavalue"], "https://www.geonames.org/{}".format(item["mainsnak"]["datavalue"]["value"])])
myfile.close()

Your problem is not in writing to the csv file, it's in decoding the json data in the first place.您的问题不在于写入 csv 文件,而在于首先解码 json 数据。

using your json data as per this question as a string, and passing it into the json.loads() function:根据此问题使用您的 json 数据作为字符串,并将其传递给 json.loads() function:

>>> import json
>>> my_json = json.loads(json_str)
>>>

(no error) (没有错误)

However, if we pass that within a list:但是,如果我们在列表中传递它:

>>> my_json = json.loads([json_str])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.4/json/__init__.py", line 312, in loads
    s.__class__.__name__))
TypeError: the JSON object must be str, not 'list'
>>>

We get the same exception that you get.我们得到与您相同的异常。

Check the structure of your resp_obj object.检查你的resp_obj object 的结构。 I think you will find that it is being passed into your function as a list.我想你会发现它作为一个列表被传递到你的 function 中。 You will want to pass in just the list item that you are interested in, instead of the list itself.您将只想传递您感兴趣的列表项,而不是列表本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM