[英]Convert json string value into int
I want to convert a string value into int from a json.我想将字符串值从 json 转换为 int。
Json杰森
[
{
"date": "23.07. 16:59",
"odd": "3.50",
"change": "+0.05"
},
{
"date": "23.07. 16:07",
"odd": "3.45",
"change": "-0.15"
}
]
I tried to convert in this way json["change"] = int(json["change"])
but got TypeError: string indices must be integers
我试图以这种方式转换
json["change"] = int(json["change"])
但得到了TypeError: string indices must be integers
You have to do something like this:你必须做这样的事情:
Json=[
{
"date": "23.07. 16:59",
"odd": "3.50",
"change": "+0.05"
},
{
"date": "23.07. 16:07",
"odd": "3.45",
"change": "-0.15"
}
]
for i in range(len(Json)):
Json[i]["change"]=int(float(Json[i]["change"]))
I guess you want to convert it to float because it will return 0 if you convert to int so you can simply try:我猜您想将其转换为浮点数,因为如果转换为 int 它将返回 0,因此您可以简单地尝试:
for i in range(len(Json)):
Json[i]["change"]=int(float(Json[i]["change"]))
You have to convert change
to a float
and not int
.您必须将
change
转换为float
而不是int
。 Iterate over the contents of JSON list and do the conversion.遍历 JSON 列表的内容并进行转换。
Here I have converted change
to float
.在这里,我已将
change
转换为float
。
import json
s = '''[
{
"date": "23.07. 16:59",
"odd": "3.50",
"change": "+0.05"
},
{
"date": "23.07. 16:07",
"odd": "3.45",
"change": "-0.15"
}
]'''
d = json.loads(s)
for i in d:
i['change'] = float(i['change'])
[{'date': '23.07. 16:59', 'odd': '3.50', 'change': 0.05}, {'date': '23.07. 16:07', 'odd': '3.45', 'change': -0.15}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.