Home > Software engineering >  How to parse an string into more workable key-values?
How to parse an string into more workable key-values?

Time:10-16

So I have the following response:

{
"errors": [
{
"errorKey": "ERROR_NO_DELIVERY_OPTIONS",
"errorParameters": "[{\"errorMessage\":\"ERROR_DELIVERY_OPTIONS_YOU_SELECTED_NOT_AVAILABLE_NOW\",\"partNumbers\":[\"19308033\",\"19114798\"]},{\"errorMessage\":\"Pickup At Seller not available for these orderItemIds\",\"orderItemIds\":[\"10315031\",\"10315032\"],\"availableShipModeId\":\"13201\"}]",
"errorMessage": "ERROR_NO_DELIVERY_OPTIONS",
"errorCode": "ERROR_NO_DELIVERY_OPTIONS"
}
]
}

Unfortunately, I'm not sure how to work with the value of "errorParameters" since it just a string and not a simple key-value like the others. How would I extract all the information so I can work with it. A co-woker mentioned parsing it but not sure what he meant by that and how. Below is a more readable value. I'm working with javascript.

[
          {
            "errorMessage": "ERROR_DELIVERY_OPTIONS_YOU_SELECTED_NOT_AVAILABLE_NOW",
            "partNumbers":
              [
                19308033,
                19114798
              ]
          },
          {
            "errorMessage": "No Shipmodes Available for these orderItemsIds",
            "orderItemIds": [
              10315031,
              10315032
            ]
          }
        ]

CodePudding user response:

You will need to use JSON.parse to transform JSON strings into a JS Object.

You'll need to do this in your code. I.E.

data.errors.forEach(e => console.log(JSON.parse(e.errorParameters)))

CodePudding user response:

You can use just JSON.parse() function, which changes string JSON representation into a JavaScript object.

const parsedErrorParameters = JSON.parse(data.errorParameters);

console.log(parsedErrorParameters[0].errorMessage); // ERROR_DELIVERY_OPTIONS_YOU_SELECTED_NOT_AVAILABLE_NOW

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

  • Related