将值写为标题

时间:2017-11-27 09:52:45

标签: python json csv parsing

我正在尝试将json响应从web保存到csv文件,问题是有更深层次,键值对要分开,只需要存储值。

代码:

import csv
import json


infile=open('oobar.json', "rb")
json_s=infile.read()
outfile=open("watsf.csv","wb")
writer=csv.writer(outfile)
count = 0

for data in(json.loads(json_s)):
    categories = data['document_tone']
    for category in categories['tone_categories']:
        for tone in category['tones']:
            if count != 5:
                header = ([tone.values()[0]])
                writer.writerow(header)
                count += 1
                writer.writerow([tone.values()[1]])
infile.close()
outfile.close()

Expected Output

Actual output:

Json响应解析并提取上述值

{
"document_tone": {
    "tone_categories": [
        {
            "category_id": "emotion_tone", 
            "tones": [
                {
                    "tone_name": "Anger", 
                    "score": 0.077068, 
                    "tone_id": "anger"
                }, 
                {
                    "tone_name": "Disgust", 
                    "score": 0.01956, 
                    "tone_id": "disgust"
                }, 
                {
                    "tone_name": "Fear", 
                    "score": 0.043762, 
                    "tone_id": "fear"
                }, 
                {
                    "tone_name": "Joy", 
                    "score": 0.764404, 
                    "tone_id": "joy"
                }, 
                {
                    "tone_name": "Sadness", 
                    "score": 0.084368, 
                    "tone_id": "sadness"
                }
            ], 
            "category_name": "Emotion Tone"
        }
    ]
}

我正在尝试将json响应从web保存到csv文件,问题是有更深层次,键值对要分开,只需要存储值。

1 个答案:

答案 0 :(得分:1)

您可以将您感兴趣的键和值添加到中间词典(示例中为tone_dict),然后使用csv.DictWriter来编写tone_dict

data = json.loads(json_s)

fieldnames = ['Anger', 'Disgust', 'Fear', 'Joy', 'Sadness']
tone_dict = {}

for tone in data['document_tone']['tone_categories'][0]['tones']:
    tone_dict[tone['tone_name']] = tone['score']

with open('temp.csv', 'w', newline='') as csv_file:
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow(tone_dict)