使用python 3将CSV转换为JSON

使用python 3将CSV转换为JSON,python,json,csv,Python,Json,Csv,我有一个这样的csv文件,没有标题,数据格式如下: {"article_id":724465,"title":"Addition of Aripiprazole Ups Major Depressive Disorder Remission","posting_time":1499934606065,"archive_date":"11-Jul-2018","short_desc":"Small increased likelihood of remission at 12 weeks in p

我有一个这样的csv文件,没有标题,数据格式如下:

{"article_id":724465,"title":"Addition of Aripiprazole Ups Major Depressive Disorder Remission","posting_time":1499934606065,"archive_date":"11-Jul-2018","short_desc":"Small increased likelihood of remission at 12 weeks in patients with major depressive disorder","article_type":"Journal","article_body":[{"article_desc":"WEDNESDAY, July 12, 2017 (HealthDay News) -- For patients with major depressive disorder (MDD), augmentation with aripiprazole is associated with an increased likelihood of remission, according to a study published in the July 11 issue of the Journal of the American Medical Association. \n\n Somaia Mohamed, M.D., Ph.D., from the VA Connecticut Healthcare System in West Haven, and colleagues examined the relative effectiveness and safety of three treatments for MDD in patients unresponsive to at least one antidepressant course. Patients were randomly assigned to switch to a different antidepressant, bupropion (switch group, 511 patients); augment current treatment with bupropion (augment-bupropion group, 506 patients); or augment with an atypical antipsychotic, aripiprazole (augment-aripiprazole group, 505 patients) for 12 weeks and up to 36 weeks (acute treatment and continuous phases). \n\n The researchers found that at 12 weeks, the remission rates were 22.3, 26.9, and 28.9 percent for the switch, augment-bupropion, and augment-aripiprazole groups; the augment-aripiprazole group exceeded the switch group in remission (relative risk, 1.3). The augment-aripiprazole group had greater response compared with the switch or augment-bupropion groups (74.3 versus 62.4 percent [relative risk, 1.19] and 65.6 percent [relative risk, 1.13], respectively). There were no significant treatment differences for relapse. The bupropion groups had more anxiety (24.3, 22.5, and 16.6 percent in the switch, augment-bupropion, and augment-aripiprazole groups, respectively). \n\n Given the small effect size and adverse effects associated with aripiprazole, further analysis including cost-effectiveness is needed to understand the net utility of this approach, the authors write. \n\n Several authors disclosed financial ties to pharmaceutical companies, including Bristol-Myers Squibb, which provided aripiprazole for use in the study.","links":[{"link_name":"Abstract/Full Text (subscription or payment may be required)","link_url":"http://jamanetwork.com/journals/jama/article-abstract/2643308"},{"link_name":"Editorial (subscription or payment may be required)","link_url":"http://jamanetwork.com/journals/jama/article-abstract/2643294"}]}],"long_desc":"For patients with major depressive disorder, augmentation with aripiprazole is associated with an increased likelihood of remission, according to a study published in the July 11 issue of the Journal of the American Medical Association.","content_url":"http://jamanetwork.com/journals/jama/article-abstract/2643294","large_image":"https://s3-ap-southeast-1.amazonaws.com/ebiz-env-qa/content/healthday/article-images/original/24ca07f28e0db094d35038ab62df7ac5?AWSAccessKeyId=AKIAI5RP6RWRC7U5V54A&Expires=1798705806&Signature=JgcWiK1lnRnhqTDUtS%2BS9mp%2BVUI%3D","medium_image":"https://s3-ap-southeast-1.amazonaws.com/ebiz-env-qa/content/healthday/article-images/medium/24ca07f28e0db094d35038ab62df7ac5?AWSAccessKeyId=AKIAI5RP6RWRC7U5V54A&Expires=1798705806&Signature=BLZKa1YPV86ZigzxJsSx9hEchm8%3D","small_image":"https://s3-ap-southeast-1.amazonaws.com/ebiz-env-qa/content/healthday/article-images/small/24ca07f28e0db094d35038ab62df7ac5?AWSAccessKeyId=AKIAI5RP6RWRC7U5V54A&Expires=1798705806&Signature=pgnNhk12ijVV9EqmN9fRFqgatxU%3D","micro_image":"http://s3-ap-southeast-1.amazonaws.com/ebiz-env-qa/content/healthday/article-images/micro/health-day-micro.png","copyright":"http://www.healthday.com/","topics":["Depression","Prescription Drugs"],"speciality":["Acupuncture","Ayurveda","Family Medicine","Homeopathy","Nutrition","Occupational Therapy","Yoga","Other","Internal Medicine","Geriatrics","Epidemology","General Medicine","Transfusion Medicine","Nursing","Pharmacology","Psychiatry","Psychology","Sexology"]}
其中,每条记录位于csv文件的单个单元格中,前一个单元格为空

csvfile = open('Article_Data.csv', 'r')
jsonfile = open('file.json', 'w')

reader = csv.DictReader(csvfile)
for row in reader:
    json.dump(row, jsonfile,indent=4)
它显示了错误。有什么想法吗?csv中的每条记录都是一个dict

这就是输出的方式:

{
    "article_id": 724465,
    "title": "Addition of Aripiprazole Ups Major Depressive Disorder Remission",
    "posting_time": 1499934606065,
    "archive_date": "11-Jul-2018",
    "short_desc": "Small increased likelihood of remission at 12 weeks in patients with major depressive disorder",
    "article_type": "Journal",
    "article_body": [
        {
            "article_desc": "WEDNESDAY, July 12, 2017 (HealthDay News) -- For patients with major depressive disorder (MDD), augmentation with aripiprazole is associated with an increased likelihood of remission, according to a study published in the July 11 issue of the Journal of the American Medical Association. \n\n Somaia Mohamed, M.D., Ph.D., from the VA Connecticut Healthcare System in West Haven, and colleagues examined the relative effectiveness and safety of three treatments for MDD in patients unresponsive to at least one antidepressant course. Patients were randomly assigned to switch to a different antidepressant, bupropion (switch group, 511 patients); augment current treatment with bupropion (augment-bupropion group, 506 patients); or augment with an atypical antipsychotic, aripiprazole (augment-aripiprazole group, 505 patients) for 12 weeks and up to 36 weeks (acute treatment and continuous phases). \n\n The researchers found that at 12 weeks, the remission rates were 22.3, 26.9, and 28.9 percent for the switch, augment-bupropion, and augment-aripiprazole groups; the augment-aripiprazole group exceeded the switch group in remission (relative risk, 1.3). The augment-aripiprazole group had greater response compared with the switch or augment-bupropion groups (74.3 versus 62.4 percent [relative risk, 1.19] and 65.6 percent [relative risk, 1.13], respectively). There were no significant treatment differences for relapse. The bupropion groups had more anxiety (24.3, 22.5, and 16.6 percent in the switch, augment-bupropion, and augment-aripiprazole groups, respectively). \n\n Given the small effect size and adverse effects associated with aripiprazole, further analysis including cost-effectiveness is needed to understand the net utility of this approach, the authors write. \n\n Several authors disclosed financial ties to pharmaceutical companies, including Bristol-Myers Squibb, which provided aripiprazole for use in the study.",
            "links": [
                {
                    "link_name": "Abstract/Full Text (subscription or payment may be required)",
                    "link_url": "http://jamanetwork.com/journals/jama/article-abstract/2643308"
                },
                {
                    "link_name": "Editorial (subscription or payment may be required)",
                    "link_url": "http://jamanetwork.com/journals/jama/article-abstract/2643294"
                }
            ]
        }
    ]
}
我可以对一条记录执行此操作,但无法对csv中的多条记录执行此操作


错误是,第一行被复制了n次,并且显示不是json格式。

我猜这就是基于注释的csv的外观:

, {"some_json": "some_value"}
, {"another_json": "another_value"}
这段代码忽略每行中的第一个空单元格,解析json,将其漂亮地打印到文件中

import csv
import json

with open('test.csv', 'r') as rf:
    reader = csv.reader(rf)
    with open('file.json', 'w') as wf:
        all_data = [json.loads(x[1]) for x in reader]
        wf.write(json.dumps(all_data, indent=4))
file.json的内容:

[
    {
        "some_json": "some_value"
    },
    {
        "another_json": "another_value"
    }
]

您想在文件
Article\u Data.csv
中漂亮地打印json
文件名有误导性,它不是“CSV”

Python»文档:
漂亮的印刷:

>>> import json
>>> my_json_dict = json.load(open('Article_Data.csv'))
>>> print json.dumps(my_json_dict, sort_keys=True,
               indent=4, separators=(',', ': '))
{
    "article_id": 724465,
    "title": "Addition of Aripiprazole Ups Major Depressive Disorder Remission",
    "posting_time": 1499934606065,
... omited for brevity

您的输入示例已经是有效的json而不是csv文件。请尝试将您的输入减少到可管理的程度。不要在我们身上写上几百个字。您可以用几十个字符来重现问题。您的示例数据是否都在CSV的一个单元格中,而前面的单元格为空?有许多行完全相同?有什么错误?@supershot是的,它在single中,previous为空。所有行都是这样的,该行第一列中的每条记录都是这样的。这不是有效的JSON输出。它是JSON写入到的文件的内容,由newline分隔。OP没有详细说明它应该如何输出,但我同意给定文件扩展名为.JSON,该文件应该是有效的JSON。。我会编辑。谢谢@supershot,唯一的问题是,它应该访问的单元格是列号“0”,而不是“1”。我编辑了代码。非常感谢。我会很好地理解这个逻辑。谢谢@supershot,唯一的问题是,它应该访问的单元格是列号“0”,而不是“1”。我编辑了代码。非常感谢。我会很好地理解这个逻辑。顺便说一下,我只想加载第一个单元格而忽略其他单元格。