How get variable (which does not exist in a message) from JSON message?

Viewed 83

I have a JSON message. And I want to return values that stand for "Brand", but in this message it does not exist, so this value needs to be replaced by another. How can I do that? I tried with try/except, however the values are not replaced.

import json

message = [
              {
                  "ID": 48,
                  "Type": "Update",
                  "UpdateType": "Quote",
                  "Key": {
                      "Service": "Online",
                      "Name": "Audi"
                  },
                  "Fields": {
                      "Buyers": 1000,
                      "Sellers": 500,
                      "Year": 2020
                  }
              }
          ]

data=json.loads(message)
#data[0]['ID']  this works as there is ID
try:
    data[0]['Brand']
except :
    9999  #no output seen
2 Answers

From your question:

I want to return values that stand for "Brand", but in this message, the "Brand does not exist, so this value is needed to be replaced by another. How can I do it?

So you want to retrieve entry from a list, then get item from the entry for example Brand.

and if there is no such Brand in the entry then add Brand item to the entry.

Am I right?

if so, your code may changed to:

import json
message = '[{"ID":48,"Type":"Update","UpdateType":"Quote","Key": {"Service":"Online","Name":"Audi"},"Fields":{"Buyers":1000,"Sellers":500,"Year":2020}}]'

data=json.loads(message)  # here message should be a json-string
#data[0]['ID']  this works as there is ID
try:
    data[0]['Brand']
except KeyError:
    # 9999  #no output seen
    data[0]['Brand'] = NewItem  # the item you want to replace

You need to itinerante thru the list and check in one of then contains the key. This being done on a python objects and not on a raw json string

message = [{"ID":48,"Type":"Update","UpdateType":"Quote","Key":{"Service":"Online","Name":"Audi"},"Fields":{"Buyers":1000,"Sellers":500,"Year":2020}}]

def item_exists_ofd(dic_list, item):
    for dic in dic_list:
        if item in dic:
            return dic
    return None

if __name__ == '__main__':
    match = item_exists_ofd(message, 'Brand')
    if match:
        print(match['Brand'])
    else:
        print('Brand, not found')

    match = item_exists_ofd(message, 'ID')
    if match:
        print(match['ID'])
    else:
        print('ID, not found')
Related