2

I'm trying to iterate over a .json file with a small script to find a attribute named 'model' and change it's value on each object. (It's a db-dump from Django).

import codecs, json

data = ""

with codecs.open("dump2.json", 'r', 'utf8') as data_file:    
    data = json.load(data_file)

for i in data:
    for key in i:
        if key[0] == 'model':
            key[1] = "app.model" #not working

with codecs.open('dump2.json', 'w', 'utf8') as f:
    json.dump(data, f)

What am I doing wrong here? I don't get any errors. And values are not changed.

7
  • 2
    Can you please show us an example of your json? Commented Aug 16, 2015 at 18:02
  • Anand, I dont think it's anything wrong with the json. It's a file generated from djangos 'dumpdata' command and it works when printing key[1] just not when assigning the new value. Commented Aug 16, 2015 at 18:06
  • Well unless you provide an example of your json, that works with your code , we would have no idea what data or i or key or anything else for that matter is? How do you think we would be able to advice what is going wrong? Commented Aug 16, 2015 at 18:07
  • @user3199840, Even if there is no problem with the json itself, it is much easier to help knowing what is making yout trouble. Otherwise advises would be based only on guesses Commented Aug 16, 2015 at 18:08
  • Ok. I'll be back with further documentation on whats going on here. Commented Aug 16, 2015 at 18:25

1 Answer 1

3

Based on some random documentation I found on the web. I assume you have such a json structure:

[
    {

        "pk": 1,
        "model": "auth.user",
        "fields":{
            "username": "test1"
        }
    },{
        "pk": 2,
        "model": "auth.user",
        "fields":{
            "username": "test2"
        }
    }
]

Using this json as example, when your code executes it iterates correctly over json keys on the line for i in data:. But on the second loop for key in i:, you are iterating over a string ("model" string). So, in this case, key[0] is 'm', key[1] is 'o' and so on...

You should try this way:

import codecs, json

data = ""

with codecs.open("dump2.json", 'r', 'utf8') as data_file:    
    data = json.load(data_file)

for i in data:
    for key in i:
        if key=="model":
            i[key] = "app.model"

with codecs.open('dump2.json', 'w', 'utf8') as f:
    json.dump(data, f)
Sign up to request clarification or add additional context in comments.

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.