使用Python:AttributeError将JSON解析为CSV:“unicode”对象没有属性“keys”

2024-05-23 15:52:11 发布

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

我有一个嵌套的JSON数据集,包含多个条目,如下所示:

{
"coordinates": null,
"acoustic_features": {
    "instrumentalness": "0.00479",
    "liveness": "0.18",
    "speechiness": "0.0294",
    "danceability": "0.634",
    "valence": "0.342",
    "loudness": "-8.345",
    "tempo": "125.044",
    "acousticness": "0.00035",
    "energy": "0.697",
    "mode": "1",
    "key": "6"
},
"artist_id": "b2980c722a1ace7a30303718ce5491d8",
"place": null,
"geo": null,
"tweet_lang": "en",
"source": "Share.Radionomy.com",
"track_title": "8eeZ",
"track_id": "cd52b3e5b51da29e5893dba82a418a4b",
"artist_name": "Dominion",
"entities": {
    "hashtags": [{
        "text": "nowplaying",
        "indices": [0, 11]
    }, {
        "text": "goth",
        "indices": [51, 56]
    }, {
        "text": "deathrock",
        "indices": [57, 67]
    }, {
        "text": "postpunk",
        "indices": [68, 77]
    }],
    "symbols": [],
    "user_mentions": [],
    "urls": [{
        "indices": [28, 50],
        "expanded_url": "cathedral13.com/blog13",
        "display_url": "cathedral13.com/blog13",
        "url": "t.co/Tatf4hEVkv"
    }]
},
"created_at": "2014-01-01 05:54:21",
"text": "#nowplaying Dominion - 8eeZ Tatf4hEVkv #goth #deathrock #postpunk",
"user": {
    "location": "middle of nowhere",
    "lang": "en",
    "time_zone": "Central Time (US & Canada)",
    "name": "Cathedral 13",
    "entities": null,
    "id": 81496937,
    "description": "I\u2019m a music junkie who is currently responsible for Cathedral 13 internet radio (goth, deathrock, post-punk)which has been online since 06/20/02."
},
"id": 418243774842929150
}

我想把它转换成一个csv文件,其中有多个列包含每个JSON对象的相应条目。下面是我编写的Python代码:

^{pr2}$

在运行上述代码时,我得到一个错误:AttributeError:'unicode'对象没有属性'keys'。 有什么问题吗?在


Tags: textnamecomidjsonurllangartist
1条回答
网友
1楼 · 发布于 2024-05-23 15:52:11

您可以一次读取JSON文件,如下所示:

with open('a.txt') as data_file:    
    data = json.load(data_file)

现在您将JSON作为data字典。在

由于您希望从JSON到csv的特定条目(例如,entities不保存到csv),您可以保留一个自定义列标题,然后在数据上循环以将特定的键写入csv:

^{pr2}$

相关问题 更多 >