【发布时间】:2014-10-29 20:00:49
【问题描述】:
鉴于以下 json...
var body = "{ \"name\": \"test\", \"description\": \"test json\", \"website\": \"domain.com\" }"
...如何删除除值中的空格之外的所有空格?
我尝试了以下正则表达式...
var body = "{ \"name\": \"test\", \"description\": \"test json\", \"website\": \"domain.com\" }".replace(/\r?\n|\r/g, "").replace(/\s+/g, "")
...但它也会删除值中的空格(即description):
{"name":"test","description":"testjson","website":"domain.com"}
我需要获取
{"name":"test","description":"test json","website":"domain.com"}
发送。
【问题讨论】:
-
我认为你错过了 JSON 的重点,因为那不是 JSON,而是一个 JavaScript 对象。你想要
JSON.stringify(body) -
JSON.stringify(body)不带空格返回。在尝试从那里删除之前,您是否尝试查看是否有空格? -
@zerkms 嗯,这是标准/保证的行为吗?
-
在实际示例中,我得到一个带有空格的 JSON 字符串...让我在我的帖子中修复这个示例。
-
新版问题:先
parse,再stringify
标签: javascript regex json