Python and CSV: Reading JSON from CSV -
i have function reads csv file , dumps contents file of choice. contents of csv file column each rows contains series of json objects this(validated jsonlint):
[{"classname": "merchant", "__type": "pointer", "objectid": "s8igowbn8y"}, {"classname": "merchant", "__type": "pointer", "objectid": "psnnxwfvmv"}, {"classname": "merchant", "__type": "pointer", "objectid": "ihcc9ikkbj"}, {"classname": "merchant", "__type": "pointer", "objectid": "rvprbh5nwx"}, {"classname": "merchant", "__type": "pointer", "objectid": "47zjn9rrov"}, {"classname": "merchant", "__type": "pointer", "objectid": "cogtlmgzyo"}, {"classname": "merchant", "__type": "pointer", "objectid": "yjhn9dbcit"}, {"classname": "merchant", "__type": "pointer", "objectid": "neoy9rprd4"}]
to conceptualize bit, want:
csv file ---> function wrote ---> something.json
in case used test.csv input , test.txt output. seems work fine first json stream, there quirk:
the first json object come out fine:
[ {"classname": "merchant", "__type": "pointer", "objectid": "s8igowbn8y"}, {"classname": "merchant", "__type": "pointer", "objectid": "psnnxwfvmv"}, {"classname": "merchant", "__type": "pointer", "objectid": "ihcc9ikkbj"}],
but after that, start coming out this:
"[{""classname"": ""merchant"", ""__type"": ""pointer"", ""objectid"": ""s8igowbn8y""}, {""classname"": ""merchant"", ""__type"": ""pointer"", ""objectid"": ""psnnxwfvmv""}, {""classname"": ""merchant"", ""__type"": ""pointer"", ""objectid"": ""ihcc9ikkbj""}, {""classname"": ""merchant"", ""__type"": ""pointer"", ""objectid"": ""rvprbh5nwx""}, {""classname"": ""merchant"", ""__type"": ""pointer"", ""objectid"": ""47zjn9rrov""}, {""classname"": ""merchant"", ""__type"": ""pointer"", ""objectid"": ""cogtlmgzyo""}, {""classname"": ""merchant"", ""__type"": ""pointer"", ""objectid"": ""yjhn9dbcit""}, {""classname"": ""merchant"", ""__type"": ""pointer"", ""objectid"": ""neoy9rprd4""}', '\n[{""classname"": ""merchant"", ""__type"": ""pointer"", ""objectid"": ""tnglb9dobr""},
here function this:
def read_csv(thefile): f = open('test.txt','w') open(thefile, 'rb') csvfile: #based on python documentation spamreader = csv.reader(csvfile, delimiter=']') row in spamreader: f.write(str(row)) f.close()
two questions:
how ensure output consistent? in other words, how can eliminate ""'s , newline characters json valid? have nlsparams i'm adding?
eventually, don't want dump .txt file, .json file. how can done?
thanks , responses!
my guess -untested- :
import json open('test.txt','r') input_file: open('output.json','wb') output_file: row in input_file.readlines(): output_file.write(json.loads(row))
in case, using lib lot: https://docs.python.org/2/library/json.html
Comments
Post a Comment