简体   繁体   中英

How to convert JSON string into integer in python?

How can I convert year and isbn into integers from this json?

({
    "title": "The Notebook",
    "author": "Nicholas Sparks",
    "year": "1996",
    "isbn": "0553816713"
})

You can simply update the values with their corresponding int values

data = {
    "title": "The Notebook",
    "author": "Nicholas Sparks",
    "year": "1996",
    "isbn": "0553816713"
    }

data["year"] = int(data["year"])
data["isbn"] = int(data["isbn"])

print(data)

OUT: {'title': 'The Notebook', 'author': 'Nicholas Sparks', 'year': 1996, 'isbn': 553816713}

Read this article , it is about json and python!

This will work:

import json

json_data =  '''{
    "title": "The Notebook",
    "author": "Nicholas Sparks",
    "year": "1996",
    "isbn": "0553816713"
}'''

python_data = json.loads(json_data)

year = int(python_data["year"])
isbn  = int(python_data["isbn"])
print(year, isbn)

json_data is a string containing the data in json format. Then, with json.loads() is converted into a python dictionary. Finally, year and isbn are being converted from string to integer.

Hope it helps:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM