Search code examples
pythonnode.jsjsonaws-lambdaamazon-sqs

How to parse a json with escaped string into smaller json with node js or python


I'm using AWS step functions and want to parse the following json with a node js or python lambda function (the language is irrelevant, I just need the results):

{
  "stage": "dev",
  "server": {
    "instanceId": "i-xxxx",
    "status": "running"
  },
  "message": [
    {
      "MessageId": "xxx",
      "ReceiptHandle": "xxx",
      "MD5OfBody": "xxx",
      "Body": "{\n  \"stage\": \"DEV\",\n  \"id\": \"5\",\n \"results\": \"D:\\\\Temp\\\\results\"\n}",
      "Attributes": {
        "SenderId": "xxxx",
        "ApproximateFirstReceiveTimestamp": "xxx",
        "ApproximateReceiveCount": "1",
        "SentTimestamp": "xxx",
        "SequenceNumber": "xxx",
        "MessageDeduplicationId": "20",
        "MessageGroupId": "20"
      }
    }
  ]
}

I just need the "message.Body"-Part. I'd like to split this into three vars for further actions:

{
  "stage":"DEV",
  "id":"5",
  "results":"D:\\Temp\\results"
}

Could someone help me with this? I just spent the last hour with JSON.stringify , parse, unescape and so on, unfortunately without success :(

Thank you in advance!


Solution

  • Does this work?

    import json
    jsondata = {
      "stage": "dev",
      "server": {
        "instanceId": "i-xxxx",
        "status": "running"
      },
      "message": [
        {
          "MessageId": "xxx",
          "ReceiptHandle": "xxx",
          "MD5OfBody": "xxx",
          "Body": "{\n  \"stage\": \"DEV\",\n  \"id\": \"5\",\n \"results\": \"D:\\\\Temp\\\\results\"\n}",
          "Attributes": {
            "SenderId": "xxxx",
            "ApproximateFirstReceiveTimestamp": "xxx",
            "ApproximateReceiveCount": "1",
            "SentTimestamp": "xxx",
            "SequenceNumber": "xxx",
            "MessageDeduplicationId": "20",
            "MessageGroupId": "20"
          }
        }
      ]
    }
    jsonbody = json.loads(jsondata.get('message')[0].get('Body'))
    print(jsonbody)
    # {'stage': 'DEV', 'id': '5', 'results': 'D:\\Temp\\results'}