简体   繁体   中英

Parse a nested Json

I have tried to parse this Json response but it seems like part of the Json is sent in some different format so when trying to parse the "Pricing" field under the "PREVIOUS_CONFIRMED_RESERVATION_SESSION_ATTRIBUTE" which is under "sessionAttributes" the result is undefined though other fields outside the "sessionAttributes" are accessible.

This is the Json file:

 {
"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"}
}

This is what I am trying to access after fetching this Json response:

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;
      });

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

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

Your PREVIOUS_CONFIRMED_RESERVATION_SESSION_ATTRIBUTE is a JSON string so you need to parse it again:

 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); 

Then in your case:

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

You should parse PREVIOUS_CONFIRMED_RESERVATION_SESSION_ATTRIBUTE in response

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;
      });

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