从JSON

时间:2015-08-31 03:31:38

标签: javascript json

我有一个JSON响应没有正确格式化并且有特殊字符,我想通过使用string.replace()删除特殊字符来清理它。由于某种原因,它无法正常工作。

这是JSON结果

[{"User::newPassword":["Password could not be changed. The request can't be validated"]},[]]

这是我的表达。

resp.replace(::g, '');

但它似乎不起作用。任何有关这方面的建议都会受到赞赏,因为在后端我无能为力。

1 个答案:

答案 0 :(得分:5)

您无法在JSON上使用replace()

如果您正在使用字符串

如果要替换第一次出现,

::应该在引号中。

resp.replace('::', '');

如果要替换所有匹配项,请使用/作为正则表达式的分隔符。

resp.replace(/::/g, '');

如果您正在使用JSON

  1. 使用JSON
  2. JSON.stringify()转换为字符串
  3. 在字符串
  4. 上使用replace
  5. 使用string
  6. JSON转换回JSON.parse()

    使用对象方法

    您还可以更改key以从中删除::

    var newKey = key.replace('::', ''); // Create new key by replacing the `::`
    obj[newKey] = obj[key]; // Add new key and value in object
    delete key; // Remove old key