Skip to content
Advertisement

Convert pandas DataFrame to list of JSON-strings

I need to know how to implement to_json_string_list() function in that case:

df = pandas.read_json('[{"rec1" : "val1", "rec2" : "val4"}, {"rec1" : "val3", "rec2" : "val4"}]', orient='records')
json_strings = list()
json_strings = to_json_string_list(df)
for json_string in json_strings:
    print(json_string)

to get output like:

{“rec1” : “val1”, “rec2” : “val4”}
{“rec1” : “val3”, “rec2” : “val4”}

I know that there are function to_json(orient='records'), but it is not that I need, because I get:

[{“rec1” : “val1”, “rec2” : “val4”},
{“rec1” : “val3”, “rec2” : “val4”}]

Printing is not only thing I will do with this strings, so simple substitution of [], is not what I need, too.

Advertisement

Answer

I think you need to_json with parameter lines=True:

print (df.to_json(orient='records', lines=True))
{"rec1":"val1","rec2":"val4"}
{"rec1":"val3","rec2":"val4"}

df.to_json('file.json',orient='records', lines=True)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement