I'm trying to convert a json file to csv. I got stuck at the following problem: I want to extract data from the undersection "snippet".
我正在尝试将json文件转换为csv。我遇到了以下问题:我想从分支“片段”中提取数据。
I was trying the following script, but it returns the error: TypeError: list indices must be integers, not str
我正在尝试以下脚本,但它返回错误:TypeError:list indices必须是整数,而不是str
#!/usr/bin/python
import json
with open('input1.json') as json_data:
data = json.load(json_data)
for r in data ['items'] ['snippet']:
print (r ['kind'])
And here is a part of json file:
这是json文件的一部分:
{
"kind": "youtube#videoListResponse",
"etag": "\"gMxXHe-zinKdE9lTnzKu8vjcmDI/a3mLolGMIuGWUS6prd_fSkWBK8c\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#video",
"etag": "\"gMxXHe-zinKdE9lTnzKu8vjcmDI/Dv8RZiEKwUBsQIzhG2G0UrgyGKA\"",
"id": "FiZlVR7UxiQ",
"snippet": {
"publishedAt": "2016-09-07T14:12:12.000Z",
"channelId": "UC8_MMK_ePSIQf0cRvX63RkQ",
"title": "Babusia - RODZINA PIRATÓW odc. 04 (PL)",
"description": "Rodzina piratów to serial animowany opowiadający o rodzinie
piratów, która mieszka na wyspie wraz z innymi mieszkańcami. Co dzień
pirat Wiktor Mac Bernic poszukuje skarbów, które są ukryte na wyspie.
Jednak przeszkadza mu w tym jego sąsiad Albert Derekin wraz z jego
rodziną. Na dodatek jego syn jest zakochany w Krewetce, czyli córce
Wiktora.",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/FiZlVR7UxiQ/default.jpg",
"width": 120,
"height": 90
},
So the question is, how to extract the itemsfrom the section 'Snippet' in this case.
所以问题是,在这种情况下如何从“Snippet”部分中提取项目。
1 个解决方案
#1
0
items
is a list; you're trying to access a field in the list, instead of an element of that list.
items是一个列表;您正在尝试访问列表中的字段,而不是该列表的元素。
It's nested as so:
它嵌套如下:
- dict list dict dict
- dict list dict dict
but you're accessing it as if it was structured like this:
但你正在访问它,好像它的结构如下:
- dict dict list dict
- dict dict list dict
Here's one way of doing it:
这是一种方法:
#!/usr/bin/python
import json
with open('input1.json') as json_data:
data = json.load(json_data)
for r in data ['items']:
snippet = r ['snippet']
print (snippet ['kind'])
#1
0
items
is a list; you're trying to access a field in the list, instead of an element of that list.
items是一个列表;您正在尝试访问列表中的字段,而不是该列表的元素。
It's nested as so:
它嵌套如下:
- dict list dict dict
- dict list dict dict
but you're accessing it as if it was structured like this:
但你正在访问它,好像它的结构如下:
- dict dict list dict
- dict dict list dict
Here's one way of doing it:
这是一种方法:
#!/usr/bin/python
import json
with open('input1.json') as json_data:
data = json.load(json_data)
for r in data ['items']:
snippet = r ['snippet']
print (snippet ['kind'])