0
import pathlib
a=pathlib.Path(__file__).parent.absolute()
dirc=str(a)+'\\file.json'
dirc2=str(a)+'\\PrettyJson.json'
data={1: {"titolo": "yea boi", "voto": 10, "genere": "a me ne so"}, 2: {"titolo": "yea boi 2", "voto": 8, "genere": "bo"}}

def jsonPrettyPrint():
    with open(dirc,'w') as json_file:
        json.dump(data, json_file)
    with open(dirc) as json_file:
        with open(dirc2,'w') as PrettyJsonFile:
            Obj = json.load(json_file)
            PrettyJson = json.dumps(Obj, indent=4)
            json.dump(PrettyJson,PrettyJsonFile)
            print(PrettyJson)

jsonPrettyPrint()

Here the code, it work properly, but when i print Pretty Json, it give as output this

{
    "1": {
        "titolo": "yea boi",
        "voto": 10,
        "genere": "a me ne so"
    },
    "2": {
        "titolo": "yea boi 2",
        "voto": 8,
        "genere": "bo"
    }
}

as u can see, 2 and 1 are strings and not intengers, but 8 and 10 are intengers, idk why, any help would be appreciated

4
  • JSON keys must be strings. That's the only allowed type according to the JSON spec. Commented Jul 14, 2020 at 7:48
  • JSON keys can only be strings. Therefore 1 and 2 are strings. Commented Jul 14, 2020 at 7:48
  • oh thanks... but i need keys to be intengers in some way, how i can? Commented Jul 14, 2020 at 7:48
  • Don't use JSON. Use something else. Commented Jul 14, 2020 at 7:50

1 Answer 1

1

Convert the keys to int after loading the JSON.

with open(dirc) as json_file:
    data = json.load(json_file)
for key, value in list(data.items()):
    data[int(key)] = value
    del data[key]
print(data)
Sign up to request clarification or add additional context in comments.

2 Comments

oh thanks i was trying to do this, but now ``` File "c:/Users/giuse/OneDrive/Desktop/Anime List/jsonHandler.py", line 21, in <module> for key, value in data.items(): RuntimeError: dictionary changed size during iteration ```
Use list(data.items()) to extract everything into a list first.

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.