将JSON转换为CSV

时间:2015-10-24 06:07:07

标签: python json csv

我正在尝试将文件(不是真正的json)转换为csv文件,这里是代码

str1 <-  "clt_Amon_CanESM2_rcp45_185001-230012.nc"

示例文件是这样的:

import json
import gzip
import csv


def parse(path):
  g = gzip.open(path, 'r')
  for l in g:
    yield json.dumps(eval(l))


csvOut = gzip.open("meta_Musical_Instruments.csv", 'w')
writer = csv.writer(csvOut)

fields = ["asin"]

for product in parse("meta_Musical_Instruments.json.gz"):
  line = []
  for f in fields:
    if product.has_key(f): line.append(product[f])
    else: line.append("")
  writer.writerow(line)

执行代码后,我收到了错误信息:

{'asin': '0014072149', 'related': {'also_viewed': ['B0058DK7RA'], 'buy_after_viewing': ['B0058DK7RA']}, 'title': 'Double Concerto in D Minor By Johann Sebastian Bach. Edited By David Oistrach. For Violin I, Violin Ii and Piano Accompaniment. Urtext. Baroque. Medium. Set of Performance Parts. Solo Parts, Piano Reduction and Introductory Text. BWV 1043.', 'price': 18.77, 'salesRank': {'Musical Instruments': 94593}, 'imUrl': 'http://ecx.images-amazon.com/images/I/41m6ygCqc8L._SY300_.jpg', 'brand': '', 'categories': [['Musical Instruments']], 'description': 'Composer: J.S. Bach.Peters Edition.For two violins and pianos.'}

请帮忙!

2 个答案:

答案 0 :(得分:0)

您似乎对json.dumps()的作用感到困惑... JSON是一种文本格式 - 数据的文本表示。 json模块允许您将Python对象编码为json或将json字符串解码为Python对象。 json.dumps(python_obj)执行Python到json编码并返回一个字符串。要从json字符串解码为Python对象,必须使用json.loads(json_string)。 IOW,你的'parse()函数应该是这样的:

def parse(path):
  g = gzip.open(path, 'r')
  for l in g:
    yield json.loads(l)

我不知道如果不知道你的&#34;不是真正的json&#34;文件包含,,这肯定是你应该如何使用json将json字符串解码为Python对象;)

作为旁注:Python中eval()的真实用例非常罕见 - 自1.5.2天以来我一直在用Python编程,到目前为止从未使用它 - ,所以如果你发现自己使用eval,那么你有99.999%的机会做错了。

答案 1 :(得分:-1)

使用双引号而不是单引号。 JSON只允许双引号

'key' - &gt; "key"

相关问题