用python,json和csv来json [英] csv to json with python, json in rows

查看:202
本文介绍了用python,json和csv来json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我尝试了下面的这个脚本,把它们放在一起答案,但这种格式:

  {
key:'value'
},
{
key:'value'
} // etc

I想要格式化为:

  {key,'value'},
{key,'value'} ,// etc

我尝试了几种建议在这里插入换行符的方法, 。

下面的脚本:

$ p $ import sys,getopt
import csv
import json

$ b CSV_PATH ='path / file.csv'
JSON_PATH ='path / demo.json'

csv_file = csv.DictReader(open(CSV_PATH,'r'))

json_list = []
for csv_file中的行:
json_list.append(row)

文件(JSON_PATH,'w')。write(json.dumps(json_list,indent = 4,separators =(', )))

我的csv很简单:

  SUM_F SUM_I SUM_P SUM_PI SUM_Bt SUM_BI SUM_M SUM_MI年月
15 3963 14 993 0 91 1 2879 2009 1
$ b

等。编辑:我收到了这个建议在另一个 $ b

 :print json.dumps(x)

这将打印我正在寻找的格式,但我还没有想出如何将其写入到json文件中。

解决方案

  import csv 
import json

CSV_PATH ='file.csv'
JSON_PATH =' demo.json'

with open(CSV_PATH,'r')as csv_file:
reader = csv.DictReader(csv_file)
with open(JSON_PA TH,'w')作为json_file:
在阅读器中的行:
json_file.write(json.dumps(row)+'\\\
')

str(row)会给出错误的引号,请不要使用它。您将无法使用 json 读取文件。


I would like to covert a CSV to a set of JSON objects with Python, formatted in rows.

I tried this script below, put together from a couple SO answers, but this formats this way:

{
   key:'value'
},
{
   key:'value'
} // etc

I would like to format this as:

{ key, 'value'},
{ key, 'value'}, // etc

I tried a few ways suggested here to insert a newline, but none worked so far.

script below:

import sys, getopt
import csv
import json


CSV_PATH = 'path/file.csv'
JSON_PATH = 'path/demo.json'

csv_file = csv.DictReader(open(CSV_PATH, 'r'))

json_list = []
for row in csv_file:
   json_list.append(row )

file(JSON_PATH, 'w').write(json.dumps(json_list, indent=4, separators=(' ,')  ))

my csv is straightforward:

SUM_F   SUM_I   SUM_P   SUM_PI  SUM_Bt  SUM_BI  SUM_M   SUM_MI  Year    Month
15       3963     14      993    0      91      1      2879     2009       1

etc..

EDIT: I received this suggestion in the comments of another post:

for x in json_list: print json.dumps(x)

this will print the format I am looking for, but I have not yet figured out how to write this to a json file.

解决方案

import csv
import json

CSV_PATH = 'file.csv'
JSON_PATH = 'demo.json'

with open(CSV_PATH, 'r') as csv_file:
    reader = csv.DictReader(csv_file)
    with open(JSON_PATH, 'w') as json_file:
        for row in reader:
            json_file.write(json.dumps(row) + '\n')

str(row) gives the wrong kind of quotes, don't use it. You won't be able to read the file with json.

这篇关于用python,json和csv来json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆