Jacky753 Jacky753 - 5 months ago 5
JSON Question

New to Python 3.4+ Scripting and Manipulating JSON

I'm currently trying to manipulate JSON with a script that I've wrote. And it is doing what I want it to do, but there's something needed to be adjust, and that is to change the Class? of the JSON? not sure if that's what is called in JSON.

"rooms": {
"1": {
"tiles": {
"-3,1": {
"x": -4,
"scaleY": 1,
"scaleX": 1,
"y": 1,
"id": "58"
},
"-2,-3": {
"x": -3,
"scaleY": 1,
"scaleX": 1,
"y": -3,
"id": "193"
},
"5,-3": {
"x": 6,
"scaleY": 1,
"scaleX": 1,
"y": -3,
"id": "58"
},
"0,-11": {
"x": -1,
"scaleY": 1,
"scaleX": 1,
"y": -11,
"id": "55"
}
}
}


These are just a snip bits of the JSON there are way more than these

I'd like to change the "-3,1" to "-4,1", I want all the "x" and "y" match the class.

like "-2,-3" to "-3,-3" , "5,-3" to "6,-3" , "-1,-11"

And I'm not sure on how to do that...

Answer

Convert your JSON string into a python object using json.loads, then you can update the inner dict at key tiles like so:

d = {"rooms": {
         "1": {
             "tiles": {
                "-3,1": {
                    "x": -4,
                    "scaleY": 1,
                    "scaleX": 1,
                    "y": 1,
                    "id": "58"
                },
                "-2,-3": {
                    "x": -3,
                    "scaleY": 1,
                    "scaleX": 1,
                    "y": -3,
                    "id": "193"
                },
                "5,-3": {
                    "x": 6,
                    "scaleY": 1,
                    "scaleX": 1,
                    "y": -3,
                    "id": "58"
                },
                "0,-11": {
                    "x": -1,
                    "scaleY": 1,
                    "scaleX": 1,
                    "y": -11,
                    "id": "55"
                }
           }
        }
    }
}
b = {}
for k, v in d['rooms']['1']['tiles'].items(): 
    b['{},{}'.format(v['x'], v['y'])] = v
d['rooms']['1']['tiles'] = b

This works for the sample you have posted. For your data, you may need to consider multiple keys in the main dictionary. Using .items() to do this is one of the possibilities.