Paul
Paul

Reputation: 177

How to add element to JSON string which depends on another element of that string in Python

I am trying to add an element to a JSON string which is made from an element value in that string. For example my string is:

{'stock': [{'weight': '80', 'warehouse': 1}, {'weight': '40', 'warehouse': 2}, {'weight': '100', 'warehouse': 1}...]}

And I want to add a text to the 'weight' element and then save that new element as 'value'. So the result should look like this:

{'products': [{'weight': '80', 'warehouse': 1, 'value': 'weight 80 lbs'}, {'weight': '40', 'warehouse': 2, 'value': 'weight 40 lbs'}, {'weight': '100', 'warehouse': 1, 'value': 'weight 100 lbs'}...]}

And my JSON string which I want to edit has much more 'products' than this example string.

Upvotes: 1

Views: 65

Answers (2)

Null
Null

Reputation: 119

A second answer if the other is confusing.

dict = {'stock': [ {'weight': '80', 'warehouse': 1}, {'weight': '40', 'warehouse': 2}, {'weight': '100', 'warehouse': 1} ]}

# loop throught keys
     # loop through values of keys
         # append new value to list

for key in dict:
    for values in dict[key]:
        values["value"] = "weight " + values["weight"]+ " lbs";

print(dict)

I would recommend learning more about dictionary manipulation.

Output

{
'stock': [
    {'weight': '80', 'warehouse': 1, 'value': 'weight 80 lbs'},
    {'weight': '40', 'warehouse': 2, 'value': 'weight 40 lbs'},
    {'weight': '100', 'warehouse': 1, 'value': 'weight 100 lbs'}
]}

Upvotes: 0

Mike67
Mike67

Reputation: 11342

It looks like you can just update the list items:

dd = {'stock': [{'weight': '80', 'warehouse': 1}, {'weight': '40', 'warehouse': 2}, {'weight': '100', 'warehouse': 1}]}

for d in dd['stock']:
    d['value'] = 'weight ' + d['weight'] + ' lbs'
    
print(dd) 

Output

{'stock': [{'weight': '80', 'warehouse': 1, 'value': 'weight 80 lbs'}, {'weight': '40', 'warehouse': 2, 'value': 'weight 40 lbs'}, {'weight': '100', 'warehouse': 1, 'value': 'weight 100 lbs'}]}

Upvotes: 1

Related Questions