Pelide
Pelide

Reputation: 528

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:

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:


[
    {
        "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"

Upvotes: 0

Views: 1972

Answers (2)

Baldrickk
Baldrickk

Reputation: 4409

Your problem is not in writing to the csv file, it's in decoding the json data in the first place.

using your json data as per this question as a string, and passing it into the 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. I think you will find that it is being passed into your function as a list. You will want to pass in just the list item that you are interested in, instead of the list itself.

Upvotes: 1

Matt L.
Matt L.

Reputation: 3621

The TypeError is telling you what the problem is. You are trying to pass a list to a function when it expects bytes or a string. 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()

Upvotes: 1

Related Questions