5

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.

3 Answers 3

17

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer, with this lines next thing I need is to split() this string by linefeed to get list?
I think yes, a = df.to_json(orient='records', lines=True) print (a.split('\n')) should work.
1

Another option using a comprehension list:

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.