0

I'm trying to convert a JSON file to CSV so I can read the data like : "id", "title", "channel ID" (sample below). I'm very beginner and it is hard to me to find a soulution. However, I'm trying the code below, and I'm receiving the error:

"File "converse.py",line 5, in (module) items_parsed = json.loads(items) NameError: name 'items' is not defined".

The script I'm using is:

import json

import csv

items_parsed = json.loads(items)

items_data = items_parsed['items']

# open a file for writing

items_data_output = open(r'C:\Users\ciszewskij\Desktop\YouTube\items_data_output.csv', 'w')

# create the csv writer object

csvwriter = csv.writer(items_data_output)

count = 0

for items in items_data:

if count == 0:

         header = items.keys()

         csvwriter.writerow(header)

         count += 1

  csvwriter.writerow(items.values())

items_data_output.close()

and here is the sample from JSON file:

    {
 "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
 },

Thank you in advance for help!

3
  • You specify items_parsed = json.loads(items) - what is items? You don't seem to assign it. Commented Dec 13, 2016 at 11:13
  • 1
    you json code is not cpmplete Commented Dec 13, 2016 at 11:17
  • Tahnks a lot for answers! Right, json code is not complete, I didn't want to past the whole code here, since it's quite large. Regarding json file and "Items": This json file is youtube#playlistItemListResponse. under Items, I understood the playlist items like "channelID", "title", "description" etc. present in the json file. So the question actually is how to convert such a file to csv. Commented Dec 13, 2016 at 13:51

1 Answer 1

1

You did not open and read the json file, that's why items is undefined.

items = open(...).read()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.