简体   繁体   中英

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.

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)

There is another method which gives you the reverse of pd.Daa

import json
json_lst = []
for i in (range(len(df)): 
    d = json.loads(df.iloc[i, :].to_json())
    json_lst.append(d)

使用理解列表的另一种选择:

[dict(v) for _, v in df.iterrows()]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM