解析嵌套的Json

时间:2019-01-08 19:46:22

标签: javascript json parsing

我尝试解析此Json响应,但似乎Json的一部分以某种不同的格式发送,因此当尝试解析“ sessionAttributes”下“ PREVIOUS_CONFIRMED_RESERVATION_SESSION_ATTRIBUTE”下的“ Pricing”字段时,结果未定义尽管可以访问“ sessionAttributes”之外的其他字段。

这是Json文件:

 {
"dialogState":"Fulfilled","intentName":"***","message":"Thank you....","messageFormat":"PlainText","responseCard":null,
    "sessionAttributes":{"PREVIOUS_CONFIRMED_RESERVATION_SESSION_ATTRIBUTE":
    "{\"ReservationType\":\"Main\",\"Pricing\":\"2000\",\"DP\":\"wedding\"}",


    "lastConfirmedReservation":"{\"ReservationType\":\"Shape\",\"Shape\":\"Round\"}"}
,"slotToElicit":null,
"slots":{"Shape":"Round"}
}

这是我在获取以下Json响应后尝试访问的内容:

await fetch(
      '****',
      {
        method: 'POST',
        headers: {
      //**** some headers
        },
        body: JSON.stringify({ inputText: clientMessage })
      }
    )
      .then(r => r.json())
      .then(r => {
          pricing = r.sessionAttributes.PREVIOUS_CONFIRMED_RESERVATION_SESSION_ATTRIBUTE.Pricing;
      });

3 个答案:

答案 0 :(得分:1)

这是因为您的PREVIOUS_CONFIRMED_RESERVATION_SESSION_ATTRIBUTE字段是一个字符串,因此在访问Pricing之前,应使用JSON.parse()将其转换为JSON。

pricing = JSON.parse(r.sessionAttributes.PREVIOUS_CONFIRMED_RESERVATION_SESSION_ATTRIBUTE).Pricing;

答案 1 :(得分:0)

您的PREVIOUS_CONFIRMED_RESERVATION_SESSION_ATTRIBUTE是JSON字符串,因此您需要再次对其进行解析:

const data = {
  "dialogState": "Fulfilled",
  "intentName": "***",
  "message": "Thank you....",
  "messageFormat": "PlainText",
  "responseCard": null,
  "sessionAttributes": {
    "PREVIOUS_CONFIRMED_RESERVATION_SESSION_ATTRIBUTE": "{\"ReservationType\":\"Main\",\"Pricing\":\"2000\",\"DP\":\"wedding\"}",


    "lastConfirmedReservation": "{\"ReservationType\":\"Shape\",\"Shape\":\"Round\"}"
  },
  "slotToElicit": null,
  "slots": {
    "Shape": "Round"
  }
};

console.log(JSON.parse(data.sessionAttributes.PREVIOUS_CONFIRMED_RESERVATION_SESSION_ATTRIBUTE).Pricing);

然后根据您的情况:

pricing = JSON.parse(r.sessionAttributes.PREVIOUS_CONFIRMED_RESERVATION_SESSION_ATTRIBUTE).Pricing;

答案 2 :(得分:0)

您应该解析PREVIOUS_CONFIRMED_RESERVATION_SESSION_ATTRIBUTE作为回应

await fetch(
      '****',
      {
        method: 'POST',
        headers: {
      //**** some headers
        },
        body: JSON.stringify({ inputText: clientMessage })
      }
    )
      .then(r => r.json())
      .then(r => {
          const responseData =  JSON.parse(r.sessionAttributes.PREVIOUS_CONFIRMED_RESERVATION_SESSION_ATTRIBUTE)
          const pricing = responseData.Pricing;
      });