5

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

({
    "title": "The Notebook",
    "author": "Nicholas Sparks",
    "year": "1996",
    "isbn": "0553816713"
})
2
  • 2
    With the parentheses around it, it is not valid JSON. Commented May 31, 2020 at 10:49
  • you should not change the isbn to an integer, as it starts with a 0. it could lead to loss of data and cause issues where multiple books could get the same isbn Commented Sep 27, 2023 at 11:51

2 Answers 2

4

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}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

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.