1

I'm trying to write new fields and their values to an existing JSON object using Python, line by line, but it keeps creating another key instead. Here is a sample code :

# my object
data_set = {'fruits':[]}

fruit_state = 'eatable'

# the values i want to insert line by line into the same JSON object
data_set['fruits'].append({'apple' : fruit_state})
data_set['fruits'].append({'strawberry' : fruit_state})
data_set['fruits'].append({'lemon' : fruit_state})

json_dump = json.dumps(data_set, indent=4)
print(json_dump)

quit()

Which gives me :

{
    "fruits": [
        {
            "apple": "eatable"
        },
        {
            "strawberry": "eatable"
        },
        {
            "lemon": "eatable"
        }
    ]
}

But I'm trying to get something so the result would be :

{
    "fruits": [
        {
            "apple": "eatable",
            "strawberry": "eatable",
            "lemon": "eatable"
        }
    ]
}

I could put every value in an array and pass it, but I really want to insert the values line by line. Would you have an idea ? Thanks in advance.

1
  • 3
    Do you actually want fruits to be a list containing a single dictionary? It would make more sense for it to just be a dictionary directly, i.e. {"fruits": {"apple": ..etc..} } Commented Jul 19, 2021 at 11:21

3 Answers 3

1

It seems you'd be better served with fruits holding the sub-object directly, instead of containing a list. Then you can just assign values directly:

data_set = {'fruits': {}}
data_set['fruits']['apple'] = fruit_state
data_set['fruits']['strawberry'] = fruit_state
data_set['fruits']['lemon'] = fruit_state
Sign up to request clarification or add additional context in comments.

2 Comments

This was my immediate thought. Adding redundant intermediate lists into JSON is a pet peeve of mine. All it does is force the consumer to add a [0] when parsing.
That method could be helpful too. Thanks for the tip.
0

Try using dict.update:

data_set['fruits'].append({})
data_set['fruits'][0].update({'apple' : fruit_state})
data_set['fruits'][0].update({'strawberry' : fruit_state})
data_set['fruits'][0].update({'lemon' : fruit_state})

1 Comment

That's what I was looking for! I see I needed to create the list first then update it with the values using its position. Thanks a lot.
0
import json
data_set = {'fruits':[{}]} 
data_set['fruits'][0]['apple'] = fruit_state
data_set['fruits'][0].update({'strawberry' : fruit_state})

json_dump = json.dumps(data_set, indent=4)
print(json_dump)

{
    "fruits": {
        "apple": "eatable",
        "strawberry": "eatable"
    }
}



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.