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"
})
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}
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.
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.