Python 格式化 JSON 以保存到文件

huangapple go评论68阅读模式
英文:

Python format json for saving to file

问题

My data looks like this:

Key1: [Key2:[{},{},...{}]]

The code something like this:

dict_={}
dict_['Key2']=all_items
dict_fin={}
dict_fin['Key1']=[dict_]
df=pd.DataFrame(dict_fin)
df.to_json(filepath, orient="records", lines=True)

I would like to have saved json like this:

{ "Key1": [{"Key2" : [{},{},...,{}]}] }

Instead, I get it like this:

{ "Key1": {"Key2" : [{},{},...,{}]} }
英文:

My data looks like this:

    Key1: [Key2:[{},{},...{}]]

The code something like this:

    dict_={}
    dict_['Key2']=all_items
    dict_fin={}
    dict_fin['Ke1']=[dict_]
    df=pd.DataFrame(dict_fin)
    df.to_json(filepath, orient="records",lines=True)

I would like to have saved json like this:

{ "Key1": [{"Key2" : [{},{},...,{}]}] }

Instead, I get it like this:

{ "Key1": {"Key2" : [{},{},...,{}]} }

答案1

得分: 2

Use the json module from the Python standard library:

import json

outer_dict = {}
some_list = [{"inner_key": "inner_value"}, {"inner_key_2": "inner_value_2"}]
outer_dict["Key1"] = some_list
json.dumps(outer_dict)

Will give you:
'{"Key1": [{"inner_key": "inner_value"}, {"inner_key_2": "inner_value_2"}]}'

英文:

Use the json module from the Python standard library:

import json

outer_dict = { }
some_list = [{"inner_key":"inner_value"}, {"inner_key_2":"inner_value_2"}]
outer_dict["Key1"] = some_list
json.dumps(outer_dict)

Will give you:
'{"Key1": [{"inner_key": "inner_value"}, {"inner_key_2": "inner_value_2"}]}'

答案2

得分: -1

I believe the errors is on the line dict_fin['Ke1']=[dict_]. You had assigned dict_['Key2'] instead:

dict_={}
dict_['Key2']=all_items
dict_fin={}
dict_fin['Ke1']=[dict_['Key2']]
df=pd.DataFrame(dict_fin)
df.to_json(filepath, orient="records", lines=True)
英文:

I believe the errors is on the line dict_fin['Ke1']=[dict_]. You had assigned dict_['Key2'] instead:

dict_={}
dict_['Key2']=all_items
dict_fin={}
dict_fin['Ke1']=[dict_['Key2']]
df=pd.DataFrame(dict_fin)
df.to_json(filepath, orient="records",lines=True)

huangapple
  • 本文由 发表于 2023年3月9日 20:51:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75684882.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定