将pandas数据框转换为json对象-pandas

问题描述:

我正在使用df.to_json()将数据帧转换为json.但这给了我一个json字符串,而不是一个对象.如何获取json对象.

I'm using df.to_json() to convert dataframe to json. But it gives me a json string and not an object. How can I get json object.

此外,当我将此数据附加到数组时,它在json前后添加单引号,并且破坏了json结构.如何导出到json对象并正确附加.

Also, when I'm appending this data to an array, it adds single quote before and after the json and it ruins the json structure. How can I export to json object and append properly.

使用的代码:

a=[]
     array.append(df1.to_json(orient='records', lines=True)) 
     array.append(df2.to_json(orient='records', lines=True)) 

结果:

['{"test:"w","param":1}','{"test:"w2","param":2}]']

所需结果:

[{"test":"w","param":1},{"test":"w2","param":2}]

我认为需要创建dict,然后转换为json:

I believe need create dict and then convert to json:

import json
d = df1.to_dict(orient='records')
j = json.dumps(d)

或者,如果可能的话:

j = df1.to_json(orient='records')