FlyingPickle
FlyingPickle

Reputation: 1133

Python json.dumps formatting

I am trying the reverse of the operation in Parsing json.dumps - Python

I have a data frame in which the row has the format:

stopLoss  takeProfit   price    id
154.79     151.79      153.784  0

I want to format the output in a JSON of the format

{
"trades" : [{
         "stopLoss": 154.79, 
        "takeProfit": 151.79, 
        "price": 153.784, 
         "id: :0
        }]

}

using json.dumps on the row yields a JSON, but the [ ] after the "trades" are missing. Like shown below:

{
"trades" : {
         "stopLoss": 154.79, 
        "takeProfit": 151.79, 
        "price": 153.784, 
         "id: :0
        }

}

How can I ensure that the [ ] are included?

Upvotes: 0

Views: 142

Answers (2)

tripleee
tripleee

Reputation: 189317

It dumps exactly the structure you pass in. If the value of the trades key is a list of dicts instead of a single dict, you get the output you want. But this has nothing with JSON to do really; it simply depends on what data you have in the argument to json.dumps().

If your code looks like

trades = csvreader.next()
j = {'trades': trades }
json.dumps(j)

then you want to change to

j = {'trades': [trades]}

Upvotes: 1

nimrodm
nimrodm

Reputation: 23779

If x is a Pandas dataframe like the one you describe:

   stopLoss  takeProfit    price  id
0    154.79      151.79  153.784   0
1    254.79      151.79  153.784   1

You can try

json.dumps(x.to_dict(orient='records'))    

This gets you almost there:

[{"stopLoss": 154.79, "takeProfit": 151.79, "price": 153.784, "id": 0},
 {"stopLoss": 254.79, "takeProfit": 151.79, "price": 153.784, "id": 1}]

To get what you need just create a dictionary:

json.dumps({ 'trades' : x.to_dict(orient='records') })

Upvotes: 1

Related Questions