简体   繁体   English

如何遍历Python中的JSON对象并保存到CSV文件?

[英]How to iterate through JSON objects in Python and save to a CSV file?

I have Python script which retrieves data from an API in JSON format (at least I think its JSON format). 我有Python脚本,它以JSON格式(至少我认为其JSON格式)从API检索数据。 I want to loop through each 'object' and write to a CSV file. 我想遍历每个“对象”并写入CSV文件。

Here is the data returned from the api: 这是从api返回的数据:

[
{
    "bids_won": "7",
    "partner_revenue": "$0.01",
    "profit": "$0.00",
    "campaign_id": "test 1", 
    "post_click_conversions": "0", 
    "total_cost": "$0.01",
    "total_media_cost": "$0.01",
    "post_view_conversions": "2", 
    "adjusted_partner_cost": "$0.01", 
    "clicks": "0",
    "day": "August 21, 2011"
},
{
    "bids_won": "30,209", 
    "partner_revenue": "$38.67", 
    "profit": "$8.92", 
    "campaign_id": "test 2", 
    "post_click_conversions": "0", 
    "total_cost": "$29.75", 
    "total_media_cost": "$29.75", 
    "post_view_conversions": "0", 
    "adjusted_partner_cost  ": "$25.26", 
    "clicks": "10", 
    "day": "August 21, 2011"
}
 ]

How can I loop through these 'objects' and write them to a CSV file? 如何遍历这些“对象”并将其写入CSV文件? My current attempt to loop through it results in the script interating through each letter.. 我当前尝试遍历它的过程导致脚本遍历每个字母。

Appreciate the help. 感谢帮助。

ps I'm using python 2.7 PS我正在使用python 2.7

To convert this to a proper csv file, with keys as a header row, something like this should do it, where "data" is the string containing your json: 要将其转换为适当的csv文件,并以键作为标题行,应执行以下操作,其中“ data”是包含json的字符串:

import json
from csv import DictWriter
dicts = json.loads(data)
the_file = open("sample.csv", "w")
writer = DictWriter(the_file, dicts[0].keys())
writer.writeheader()
writer.writerows(dicts)
the_file.close()

Note that as of Python 2.6, simplejson has been included in the standard library as "json". 请注意,自Python 2.6起,simplejson已作为“ json”包含在标准库中。

import json
import csv
temp = json.load(open('filename.json','r'))
output =[]
for each in temp:
     row = {}
     row['field1'] =each['field1']
     row['field2'] = each['field2']
     output.append(row)
file = open( "filename_destination.csv", "w")

fileWriter = csv.writer(file , delimiter=",",quotechar='"', quoting=csv.QUOTE_MINIMAL)

Header = ['field1','field2']

fileWriter.writerow(Header)

for x in output:
te = [x['field1'],x['field2']]
fileWriter.writerow(te)
file.close()

Try using simplejson to convert the JSON string to a native Python object. 尝试使用simplejson将JSON字符串转换为本地Python对象。 You should then be able to loop through the objects using a standard for loop. 然后,您应该能够使用标准的for循环遍历对象。

http://pypi.python.org/pypi/simplejson/ http://pypi.python.org/pypi/simplejson/

data = simplejson.loads(JSON_STRING)

This will do it: 可以做到这一点:

import json
for i in json.loads(json_string):
    print ','.join(i)

See json module docs 请参阅json模块文档

You should use simplejson : http://pypi.python.org/pypi/simplejson/ 您应该使用simplejsonhttp : //pypi.python.org/pypi/simplejson/

With simplejson you can simply do: 使用simplejson,您可以简单地执行以下操作:

import simplejson as json

info = """[
{
    "bids_won": "7",
    "partner_revenue": "$0.01",
    "profit": "$0.00",
    "campaign_id": "test 1", 
    "post_click_conversions": "0", 
    "total_cost": "$0.01",
    "total_media_cost": "$0.01",
    "post_view_conversions": "2", 
    "adjusted_partner_cost": "$0.01", 
    "clicks": "0",
    "day": "August 21, 2011"
},
{
    "bids_won": "30,209", 
    "partner_revenue": "$38.67", 
    "profit": "$8.92", 
    "campaign_id": "test 2", 
    "post_click_conversions": "0", 
    "total_cost": "$29.75", 
    "total_media_cost": "$29.75", 
    "post_view_conversions": "0", 
    "adjusted_partner_cost  ": "$25.26", 
    "clicks": "10", 
    "day": "August 21, 2011"
}
 ]"""

data = json.loads(info)

And data will be a python list that you can iterate through. 并且data将是您可以循环访问的python列表。

In the end I was given a slightly different URL for the request which returned raw CSV. 最后,我为请求返回了一个略有不同的URL,该URL返回了原始CSV。 I dumped the content into a CSV file: 我将内容转储到CSV文件中:

f = open('report.csv', 'wb')
f.write(response_content)
f.close

Its not an ideal solution because I still cannot loop through the CSV objects (goes through each character) but I'm able to create a resonably well formatted csv file so its ok for now. 这不是理想的解决方案,因为我仍然无法遍历CSV对象(遍历每个字符),但是我能够创建格式合理的csv文件,因此现在还可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM