0

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" : [{},{},...,{}]} }
matszwecja
  • 6,357
  • 2
  • 10
  • 17
Nikky Leed
  • 1
  • 1
  • 2
  • 3
    why use pandas DataFrame? Are you aware of `json` module and its `.dump` method for saving a dictionary directly to json file? – matszwecja Mar 09 '23 at 12:55
  • cool, json worked fine. I need final encoding of the file UTF-16 LE BOM. How do I set encoding? – Nikky Leed Mar 09 '23 at 13:14
  • https://stackoverflow.com/questions/18337407/saving-utf-8-texts-with-json-dumps-as-utf-8-not-as-a-u-escape-sequence – matszwecja Mar 09 '23 at 13:18

2 Answers2

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"}]}'

chiashurb
  • 31
  • 4
-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)
Ramon Moraes
  • 477
  • 7
  • 23