【问题标题】:How to Parse "string data with newline symbol" to JSON Obejct?如何将“带有换行符的字符串数据”解析为 JSON 对象?
【发布时间】:2022-01-18 10:08:30
【问题描述】:

我将使用 AWS 提供的 API Gateway 和 Lambda 创建一个简单的加密服务器。

API Gateway 远程办公 HTTP API 方法,支持 Payload 2.0 版本的 Payload。

这个Payload的一个例子如下。

{
  "version": "2.0",
  "routeKey": "$default",
  "rawPath": "/my/path",
  "rawQueryString": "parameter1=value1&parameter1=value2&parameter2=value",
  "cookies": [
    "cookie1",
    "cookie2"
  ],
  "headers": {
    "header1": "value1",
    "header2": "value1,value2"
  },
  "queryStringParameters": {
    "parameter1": "value1,value2",
    "parameter2": "value"
  },
  "requestContext": {
    "accountId": "123456789012",
    "apiId": "api-id",
    "authentication": {
      "clientCert": {
        "clientCertPem": "CERT_CONTENT",
        "subjectDN": "www.example.com",
        "issuerDN": "Example issuer",
        "serialNumber": "a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1",
        "validity": {
          "notBefore": "May 28 12:30:02 2019 GMT",
          "notAfter": "Aug  5 09:36:04 2021 GMT"
        }
      }
    },
    "authorizer": {
      "jwt": {
        "claims": {
          "claim1": "value1",
          "claim2": "value2"
        },
        "scopes": [
          "scope1",
          "scope2"
        ]
      }
    },
    "domainName": "id.execute-api.us-east-1.amazonaws.com",
    "domainPrefix": "id",
    "http": {
      "method": "POST",
      "path": "/my/path",
      "protocol": "HTTP/1.1",
      "sourceIp": "IP",
      "userAgent": "agent"
    },
    "requestId": "id",
    "routeKey": "$default",
    "stage": "$default",
    "time": "12/Mar/2020:19:03:58 +0000",
    "timeEpoch": 1583348638390
  },
  "body": "Hello from Lambda",
  "pathParameters": {
    "parameter1": "value1"
  },
  "isBase64Encoded": false,
  "stageVariables": {
    "stageVariable1": "value1",
    "stageVariable2": "value2"
  }
}

在这个 Payload 中,我想用 json 解析和利用的数据是一个 body 值。

Lambda本身提供的测试没有任何问题,但是当postman在application/json方法中发送请求时,body以无法解析成json的字符串格式包含在payload中。

一个例子如下。

"[\r\n    {\r\n        \"key\" : \"aaa\",\r\n        \"value\" : \"value1\"\r\n    },\r\n    {\r\n        \"key\" : \"bbb\",\r\n        \"value\" : \"value2\"\r\n    }\r\n]"

原来的body值是这样的。

[
    {
        "key" : "aaa",
        "value" : "value1"
    },
    {
        "key" : "bbb",
        "value" : "value"
    }
]

我在解析为 json 时将使用的语言是 JavaScript。

我应该怎么做才能将这个“字符串化数据”解析为 JSON??

【问题讨论】:

  • 只要使用JSON.parse

标签: javascript json aws-lambda


【解决方案1】:

您的字符串可以使用 JSON.parse() 转换为 JSON

var data = "[\r\n    {\r\n        \"key\" : \"aaa\",\r\n        \"value\" : \"value1\"\r\n    },\r\n    {\r\n        \"key\" : \"bbb\",\r\n        \"value\" : \"value2\"\r\n    }\r\n]"

console.log(JSON.parse(data))

【讨论】:

  • OMG...我之前一直在尝试这种方法,但由于错误而无法正常工作。但是现在我已经尝试过了,它应用得非常顺利!谢谢您的帮助!! @Deepak
猜你喜欢
  • 1970-01-01
  • 2013-03-12
  • 1970-01-01
  • 1970-01-01
  • 2015-11-21
  • 2019-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多