[英]How do I remove trailing white spaces but not white spaces within a string (nor at the beginning)?
[英]JavaScript: how do I remove all the white spaces from a JSON string except the ones in the values?
鑒於以下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"}
TX。
var body = ' { "name": "test", "description": "test json", "website": "domain.com" } ';
JSON.stringify(JSON.parse(body))
返回:
{"name":"test","description":"test json","website":"domain.com"}
這正是你想要的。 是的,帶有1個參數的JSON.stringify
可以保證提供最短的JSON,這意味着鍵和值之外沒有過時的空格。 這是默認值,因為在幾乎所有情況下,JSON都是一種高效的遞歸數據序列化方法 - 默認情況下不需要使用不必要的空格。
JSON.stringify(value[, replacer [, space]])
可選的第三個參數默認為false
- 如果設置為另一個值,它會生成帶有額外空格或引入字符串的“漂亮打印”:
space參數可用於控制最終字符串中的間距。 如果是數字,則字符串化中的連續級別將由這么多空格字符(最多10個)縮進。 如果它是一個字符串,則連續的級別將由此字符串(或其前十個字符)縮進。
最后一點,你甚至不應該要使用正則表達式這一點。 Regexp用於理解字符模式,而不是用於處理XML,HTML或JSON等結構化數據。 在這些情況下,分別使用XML,DOM或JSON解析器並在那里處理結果。
解析JSON,然后再次對其進行字符串化。 解析它會將JSON轉換為Javascript對象,然后對其進行字符串化將返回最短的JSON表示:
var body = JSON.stringify(JSON.parse("{ \"name\": \"test\", \"description\": \"test json\", \"website\": \"domain.com\" }"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.