Ben J
Ben J

Reputation: 147

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

Upvotes: 0

Views: 77

Answers (3)

аlex
аlex

Reputation: 5698

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

Upvotes: 0

semanser
semanser

Reputation: 2348

This is because your PREVIOUS_CONFIRMED_RESERVATION_SESSION_ATTRIBUTE field is a string, so you should convert it to JSON with JSON.parse(), before accessing to Pricing.

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

Upvotes: 1

quirimmo
quirimmo

Reputation: 9988

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;

Upvotes: 0

Related Questions