【问题标题】:How to parse json using Jquery or Javascript如何使用 Jquery 或 Javascript 解析 json
【发布时间】:2018-04-11 14:57:40
【问题描述】:

我在 Jquery Ajax 中使用 Web 服务,这会返回以下字符串

{"d":"[{\"username\":\"ABC\",\"designation\":\"\"}]"}

但是当我试图解析这个时它给了我错误

var response = '{"d":"[{\"username\":\"ABC\",\"designation\":\"\"}]"}';

console.log(JSON.parse(response));

【问题讨论】:

  • 那是无效的 json。 [] 周围不应有引号,并且不应转义引号。这个json是怎么生成的?
  • 您能否分享更多代码(到目前为止您尝试了什么)和确切的错误消息?
  • 我正在调用其他客户提供的 Web 服务 ....我必须通过提供 Jquery Ajax 调用从中提取数据
  • var obj = jQuery.parseJSON(result); //结果表示 {"d":"[{\"username\":\"ABC\",\"designation\":\"\"}]"}

标签: java jquery ajax


【解决方案1】:

正如其他人所指出的,您需要删除大括号周围的引号。

const PATTERNS = [/"(\[)/g, /(\])"/g]; // Invalid patterns
const JsonFixer = json => PATTERNS.reduce((s, re) => s.replace(re, '$1'), json);

var rawJsonResponse = '{"d":"[{\"username\":\"ABC\",\"designation\":\"\"}]"}';

console.log(JSON.parse(JsonFixer(rawJsonResponse)));
.as-console-wrapper { top: 0; max-height: 100% !important; }

【讨论】:

    猜你喜欢
    • 2012-02-15
    • 2014-06-12
    • 1970-01-01
    • 1970-01-01
    • 2011-12-12
    • 1970-01-01
    • 2012-05-07
    • 1970-01-01
    相关资源
    最近更新 更多