1

I have a JSON file like this:

{
   "Location":true,
   "adddress":[
      {
         "street1":" 1 58 4 16"
      },
      {
         "street2":" 3 76 57 12"
      }
      {
        "street3:":....
      }
      ...
      {
        "streetn":...
      }
   ]
}

I want to add 10 to the last data of street1, street2 ....so the output looks like this how to achieve this:

Expected output:

{
   "Location":true,
   "adddress":[
      {
         "street1":" 1 58 4 26"
      },
      {
         "sttreet2":" 3 76 57 22"
      }
   ]
}
1
  • you should show us what you have tried and then we can respond with suggestions to correct/improve your code. You should be doing your own work to learn the material either for yourself, school or work. Commented Oct 30, 2022 at 22:41

5 Answers 5

1

Assuming that the data is stored in the variable json

json = { "Location": True, "adddress": [ { "street1": " 1 58 4 16" }, { "sttreet2": " 3 76 57 12" }, ] }

As the names are different (street1, sttreet2), there are various approaches.

One, that one would be able to use for more cases, would be as follows

for i in range(len(json['adddress'])):
    for key in json['adddress'][i]:
        json['adddress'][i][key] = json['adddress'][i][key][:-2] + str(int(json['adddress'][i][key][-2:]) + 10)

[Out]:

{'Location': True,
 'adddress': [{'street1': ' 1 58 4 26'}, {'sttreet2': ' 3 76 57 22'}]}

Another one, would be more manual, and it would require one to change the respective value. For example, for street1, it would be as follows

json['adddress'][0]['street1'] = json['adddress'][0]['street1'][:-2] + str(int(json['adddress'][0]['street1'][-2:]) + 10)

[Out]:

{'Location': True,
 'adddress': [{'street1': ' 1 58 4 26'}, {'sttreet2': ' 3 76 57 12'}]}

For sttreet2 it would be as follows

json['adddress'][1]['sttreet2'] = json['adddress'][1]['sttreet2'][:-2] + str(int(json['adddress'][1]['sttreet2'][-2:]) + 10)


[Out]:

{'Location': True,
 'adddress': [{'street1': ' 1 58 4 16'}, {'sttreet2': ' 3 76 57 22'}]}
Sign up to request clarification or add additional context in comments.

Comments

1

Let's say dct is your dictionary. Then:

for d in dct['adddress']:
    k = next(iter(d)) # assume there's only one key in d
    vals = d[k].split()
    vals[-1] = str(int(vals[-1]) + 10)
    d[k] = ' '.join(vals)

The assumption I made is that each dictionary in the dct['adddress'] list contains only one key.

Result:

>>> dct
{'Location': True, 'adddress': [{'street1': '1 58 4 26'}, {'sttreet2': '3 76 57 22'}]}

Comments

0
import json

json_data = """
{
  "Location": true,
  "adddress": [
    {
      "street1": " 1 58 4 16"
    },
    {
      "sttreet2": " 3 76 57 12"
    }
  ]
}
"""
var_add = 10
data = json.loads(json_data)
print(data["adddress"][0])
dict1 = data["adddress"][0]
for keys, value in dict1.items():
    print("Before adding: ", value) # 1 58 4 16
    lastTwo = int(value[-2:])
    # print 16
    # print(lastTwo)
    replacementStr = str(lastTwo + var_add)
    # prints 26
    # print(replacementStr)
    # replaces last two
    value = value[:-2] + replacementStr
    print("After adding: ", value) # 1 58 4 26

# Output:

{'street1': ' 1 58 4 16'}
Before adding:   1 58 4 16
After adding:   1 58 4 26

Comments

0

Use this code:

def get(num):
    global data
    key = data["adddress"][num].keys()[0]
    sp = [int(i) for i in data["address"][num][key].split()]
    sp[-1] += 10
    sp = [str(i) for i in sp]
    data["adddress"][num][key][num][key] = " ".join(sp)
for i in range(len(data["address"])):
    get(i)

This code returns:

{'Location': True, 'adddress': [{'street1': '1 58 4 26'}, {'sttreet2': '3 76 57 22'}]}

Comments

-1
new_address = []
for street in a['adddress']:
    key = list(street.keys())[0]
    value = list(street.values())[0]

    list_value = value.split(' ')
    list_value[-1] = str(int(list_value[-1]) + 10)
    new_value = ' '.join(list_value)
    new_street = {key: new_value}
    
    new_address.append(new_street)
    
a['adddress'] = new_address

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.