0

I want to convert a string value into int from a json.

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

1
  • 1
    Your data structure is called 'json' ? Commented Jul 24, 2021 at 10:46

2 Answers 2

1

You have to convert change to a float and not int. Iterate over the contents of JSON list and do the conversion.

Here I have converted change to 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}]
Sign up to request clarification or add additional context in comments.

1 Comment

"You have to convert change to a float and not int." is not the real answer to the OP'S question. Their main error was that they did not even parse the JSON in the first place.
1

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:

for i in range(len(Json)):
    Json[i]["change"]=int(float(Json[i]["change"]))

1 Comment

The OP has JSON, not a list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.