英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论