简体   繁体   中英

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!

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'}

Here is my way of implementing it in Python,

import json

dic = {
  "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"
      }
    }
  ]
}

message_body_str = dic['message'][0]['Body']
print(json.dumps(json.loads(message_body_str)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM