skylxne_
skylxne_

Reputation: 3

Parse JSON value into key-value attributes

I got the following output from my API:

{
'Type': 'Notification',
'MessageId': 'xxx',
'TopicArn': 'xxx',
'Subject': 'xxx',
'Message': 'EventType=Delete, FriendlyType=was deleted, '
           'Timestamp=2021-11-08T15:30:45Z, UserId=1111, [email protected], '
           'IPAddr=(empty), AccountId=22222, AccountName=test-account, '
           'ProjectId=test-project',
'Timestamp': '2021-11-08T15:30:46.214Z',
'SignatureVersion': '1'
}

Now I want to access the "Message" variable - once I am in, and get the following output (as already visible in the previous mentioned JSON):

EventType=Delete, FriendlyType=was deleted, Timestamp=2021-11-08T15:30:45Z, UserId=1111, [email protected], IPAddr=(empty), AccountId=22222, AccountName=test-account, ProjectId=test-project

How can I now access the keys like EventType, FriendlyType, etc.? I assume that I have to convert this output at first to a valid JSON, but I am currently baffled.

Upvotes: 0

Views: 465

Answers (4)

Latra
Latra

Reputation: 522

In case that you are not able to receive the Message data as a JSON, a way to handle the situation is convert the message string into a dict <key>:<value>:

message_as_dict = dict(map(lambda var: var.strip().split("=") ,message.split(",")))

NOTICE the .strip() in order to remove the spaces on the beginning of the key.

That shoud create a dictionary with the following structure:

{'EventType': 'Delete', 'FriendlyType': 'was deleted', 'Timestamp': '2021-11-08T15:30:45Z', 'UserId': '1111', 'UserName': '[email protected]', 'IPAddr': '(empty)', 'AccountId': '22222', 'AccountName': 'test-account', 'ProjectId': 'test-project'}

Then you can access to the values with, for example:

print(message_as_dict["UserName"])
> [email protected]

Upvotes: 1

martineau
martineau

Reputation: 123501

You could do it by splitting the 'Message' string up into (key, value) pairs and constructing a dictionary from them:

from pprint import pprint

output = {'Type': 'Notification',
          'MessageId': 'xxx',
          'TopicArn': 'xxx',
          'Subject': 'xxx',
          'Message': 'EventType=Delete, FriendlyType=was deleted, '
                     'Timestamp=2021-11-08T15:30:45Z, UserId=1111, [email protected], '
                     'IPAddr=(empty), AccountId=22222, AccountName=test-account, '
                     'ProjectId=test-project',
          'Timestamp': '2021-11-08T15:30:46.214Z',
          'SignatureVersion': '1'}

msg_dict = dict(pair.split('=') for pair in output['Message'].split(', '))
pprint(msg_dict, sort_dicts=False)

Output:

{'EventType': 'Delete',
 'FriendlyType': 'was deleted',
 'Timestamp': '2021-11-08T15:30:45Z',
 'UserId': '1111',
 'UserName': '[email protected]',
 'IPAddr': '(empty)',
 'AccountId': '22222',
 'AccountName': 'test-account',
 'ProjectId': 'test-project'}

Upvotes: 0

MuzaffarShaikh
MuzaffarShaikh

Reputation: 440

As mentioned in one of the answer, you can parse your Message string, but I too feel it won't be the best solution. What I noticed is that your JSON is not in proper format. See below for proper JSON you should be getting from your API.

{
  "Type": "Notification",
  "MessageId": "xxx",
  "TopicArn": "xxx",
  "Subject": "xxx",
  "Message": {
    "EventType": "Delete",
    "FriendlyType": "was deleted",
    "Timestamp": "2021-11-08T15:30:45Z",
    "UserId": "1111",
    "UserName": "[email protected]",
    "IPAddr": "(empty)",
    "AccountId": "22222",
    "AccountName": "test-account",
    "ProjectId": "test-project"
  },
  "SignatureVersion": "1"
}

Once you are able to get this output, you may further access nested objects. For example, to access FriendlyType from Message, you can simply say, body.Message.FriendlyType. body here means your entire JSON object.

Upvotes: 0

Ulises Bussi
Ulises Bussi

Reputation: 1725

you can parse your string spliting and then use it to create a dict. Maybe it's not the best solution but it's a simple one.

response = {
'Type': 'Notification',
'MessageId': 'xxx',
'TopicArn': 'xxx',
'Subject': 'xxx',
'Message': 'EventType=Delete, FriendlyType=was deleted, Timestamp=2021-11-08T15:30:45Z, UserId=1111, [email protected], IPAddr=(empty), AccountId=22222, AccountName=test-account, ProjectId=test-project',
'Timestamp': '2021-11-08T15:30:46.214Z',
'SignatureVersion': '1'
}


keyVals = [el.split('=')  for el in  response['Message'].split(', ')]

subdict = {}
for key,val in keyVals:
    subdict[key] = val
    

Upvotes: 1

Related Questions