Kuba
Kuba

Reputation: 5

Converting JSON file to CSV in Python

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!

Upvotes: 0

Views: 1694

Answers (1)

Maurice Meyer
Maurice Meyer

Reputation: 18106

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

items = open(...).read()

Upvotes: 1

Related Questions