How to convert JSON string into integer in python?

Question:

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

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

||

Answers:

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}
Answered By: Nico Müller

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.

Answered By: Levente Simofi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.