【问题标题】:How to convert string to json in Javascript如何在Javascript中将字符串转换为json
【发布时间】:2021-01-16 13:58:29
【问题描述】:

在我的应用程序中,我收到如下响应

{"success":true,"data":"{\"status\": \"Failed\", \"percentage_completed\": \"0\", \"actions\": \"Error: Insufficient argument: 1\\n\"}","message":"Logs fetched successfully."}

如何将其转换为 JSON。尝试过 JSON.parse 似乎不起作用。有没有其他方法可以将此字符串转换为有效的 JSON 格式

【问题讨论】:

  • 该字符串已经在JSON format 中。您的意思是要将其解析为 JavaScript 对象吗?
  • JSON.parse() 没用怎么办?您收到错误消息了吗?
  • 这能回答你的问题吗? How to parse JSON string in Typescript
  • 看起来这是 ajax 调用响应。你想使用JSON.parse(response.data)

标签: javascript json


【解决方案1】:

我了解混乱的来源。提供的对象有一个包含 JSON 字符串的属性。在这种情况下,“数据”属性包含您需要解析的 JSON 字符串。看下面的例子。

var result = {"success":true,"data":"{\"status\": \"Failed\", \"percentage_completed\": \"0\", \"actions\": \"Error: Insufficient argument: 1\\n\"}","message":"Logs fetched successfully."};

JSON.parse(result); // should fail
JSON.parse(result["data"]); // should work
JSON.parse(result.data) // or if you prefer this notation

【讨论】:

    猜你喜欢
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多