0

I have a similar Json structure:

{
    "test": [
        {
            "name1": "tap",
            "name2": "Tik; eev; asdv; asdfa; sadf"
        },
        {
            "name1": "Pap",
            "name2": "Tik; eev; asdv; asdfa; sadf"
        }
    ]
}

I want the value of the key name2 to be a list. For example:

The value "Tik; eev; asdv; asdfa; sadf" replaced with ['Tik', ' eev', ' asdv', ' asdfa', ' sadf']

This is what I have done but I can't update the json into new one.

import json

with open('testJson.json') as f:
    data = json.load(f)

for x in data['test']:
    string = x['name2']
    my_list = string.split(";")
    string = my_list


with open('testdata.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=4)

When I open the testdata.json its the same.

2 Answers 2

2

You need to assign the split list back to the data. In your code, you are just discarding it. You're treating x['name2'] like a reference to a string rather than a string value. You can't assign it to another variable and expect that to be reflected in the data structure- you need to explicitly update the data structure with the new value.

import json

with open('testJson.json') as f:
    data = json.load(f)

for x in data['test']:
    string = x['name2']
    my_list = string.split(";")
    x['name2'] = my_list


with open('testdata.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=4)
Sign up to request clarification or add additional context in comments.

1 Comment

Do you also know how to append the name1 value into the name2 array?
1

When you do

string = ingredient['name2']
[...]
string = my_list

you're getting the string without the context it was in. - string is just a name that stores some contents, it doesn't link back to the ingredient dictionary.

You need to change the final line here to ingredient['name2'] = my_list so that you change the insides of the dictionary, not some local string. ;)

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.