[英]Python json.dumps formatting
I am trying the reverse of the operation in Parsing json.dumps - Python我在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我想将 output 格式化为 JSON 格式
{
"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.在行上使用 json.dumps 会产生 JSON,但“交易”之后的 [ ] 缺失。 Like shown below:如下图所示:
{
"trades" : {
"stopLoss": 154.79,
"takeProfit": 151.79,
"price": 153.784,
"id: :0
}
}
How can I ensure that the [ ] are included?如何确保包含 [ ]?
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.它会准确转储您传入的结构。如果trades
键的值是字典列表而不是单个字典,您将获得所需的 output。 But this has nothing with JSON to do really;但这与 JSON 无关; it simply depends on what data you have in the argument to json.dumps()
.它仅取决于您在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]}
If x
is a Pandas dataframe like the one you describe:如果x
是 Pandas dataframe 就像您描述的那样:
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') })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.