【问题标题】:How to parse an string into more workable key-values?如何将字符串解析为更可行的键值?
【发布时间】:2021-10-15 21:17:16
【问题描述】:

所以我有以下回应:

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

不幸的是,我不确定如何使用“errorParameters”的值,因为它只是一个字符串,而不是像其他的简单键值。我将如何提取所有信息以便我可以使用它。一位同事提到解析它,但不确定他的意思是什么以及如何。下面是一个更具可读性的值。我正在使用 javascript。

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

【问题讨论】:

  • 这是 JSON,所以试试JSON.parse()

标签: javascript json parsing


【解决方案1】:

您需要使用JSON.parse 将 JSON 字符串转换为 JS 对象。

您需要在代码中执行此操作。即。

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

【讨论】:

    【解决方案2】:

    您可以只使用 JSON.parse() 函数,它将字符串 JSON 表示更改为 JavaScript 对象。

    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

    【讨论】:

      猜你喜欢
      • 2018-08-12
      • 1970-01-01
      • 2010-09-07
      • 2013-05-18
      • 2023-04-03
      • 2019-09-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多