-3

I have dynamically generated JSON file with data. Some of the data generate error of an invalid json:

SyntaxError: JSON.parse: bad control character in string literal at line 34447 column 24 of the JSON data

I located problems and some of these are

"live_href": "http://   http://google.com",
or
"login_pass": "bourdfthuk.midas.admin   r3adqerds7one",

I already fixed whitespace at the beginning and end with .trim() but trim won't remove whitespace in the center of a string.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Katerpiler
  • 119
  • 8

3 Answers3

4

Use this

str.replace(/\s/g,'')

The g repeats for all whitespace instances and the s is for all white spaces and not just the literal characters.

schylake
  • 434
  • 3
  • 14
  • 1
    Actually no, this doesn't work correctly. It makes json valid but it removes all spaces which makes other things wrongly formated. I have site names like "North Dakota Server Site" and that becomes "NorthDakotaServerSite". – Katerpiler Dec 15 '17 at 14:34
1

I see what you are trying to do. In that case, you will have to loop through your string like so:

var word = "North Dakota       Blah blah";
word = word.split(' ');
for (var x = 0; x < word.length; x++) {
    if (word[x] === "") {
      word.splice(x, 1);
      x--;
  }
}
word = word.join(' ');
console.log(word);

Working example: https://jsfiddle.net/85sj4ay6/2/

David Anthony Acosta
  • 4,766
  • 1
  • 19
  • 19
0

As someone already mentioned, your json is invalid, so you therefore cannot parse it into JSON. However, if it was valid, it would essentially work like this:

var myJson = {"login_pass": "bourdfthuk.midas.admin   r3adqerds7one"};

myJson.login_pass = myJson.login_pass.replace(/ /g, '');
console.log(myJson);

Working example: https://jsfiddle.net/85sj4ay6/

David Anthony Acosta
  • 4,766
  • 1
  • 19
  • 19