Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
67
rated 0 times [  74] [ 7]  / answers: 1 / hits: 44341  / 10 Years ago, thu, september 4, 2014, 12:00:00

Given the following json...



var body = { name: test, description: test json, website: domain.com }


... how do I remove all the white spaces except the ones in the values?



I've tried the following regexp...



var body = { name: test, description: test json, website: domain.com }.replace(/r?n|r/g, ).replace(/s+/g, )


... but it also removes the spaces in the values (i.e. description):



{name:test,description:testjson,website:domain.com}


I need to obtain



{name:test,description:test json,website:domain.com}


Tx.


More From » regex

 Answers
35
var body = ' { name: test, description: test json, website: domain.com } ';
JSON.stringify(JSON.parse(body))


Returns:



{name:test,description:test json,website:domain.com}


Which is exactly what you want. And yes, JSON.stringify with 1 parameter is guaranteed to give the shortest possible JSON, meaning no obsolete whitespace outside keys and values. That's the default because JSON is, in nearly all situations, intended to be a highly efficient recursive data serialization method - unnecessary whitespace has no use there by default.



The full syntax is actually:



JSON.stringify(value[, replacer [, space]])


The optional third parameter defaults to false - if set to another value it produces 'pretty print' with extra whitespace or lead-in strings:




The space argument may be used to control spacing in the final string.
If it is a number, successive levels in the stringification will each
be indented by this many space characters (up to 10). If it is a
string, successive levels will indented by this string (or the first
ten characters of it).




As a final note, you shouldn't even want to use a regexp for this. Regexps are for making sense out of character patterns, not for processing structured data like XML, HTML or JSON. In those cases, use an XML, DOM or JSON parser respectively and process the results in there.


[#69570] Monday, September 1, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
breonnamayah

Total Points: 574
Total Questions: 115
Total Answers: 96

Location: England
Member since Sun, May 21, 2023
1 Year ago
breonnamayah questions
;