skip to Main Content

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" : [{},{},...,{}]} }

2

Answers


  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)
    
    Login or Signup to reply.
  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"}]}'

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search