Bazinga777
Bazinga777

Reputation: 5281

String replace from JSON

I have a JSON response that is not properly formatted and has speical characters coming in and I want to clean it up by removing the special characters using string.replace(). For some reason it is not working.

Here is the JSON result

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

and here is my expression.

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

But it doesn't seem to work. Any advice on this would be appreciated as there is nothing I can do for it on the backend.

Upvotes: 0

Views: 7790

Answers (1)

Tushar
Tushar

Reputation: 87203

You cannot use replace() on JSON.

If you're working with strings

:: should be in quotes if you want to replace first occurrence of it.

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

If you want to replace all occurrences, use / as delimiter of regex.

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

If you're working with JSON

  1. Convert the JSON to string using JSON.stringify()
  2. Use replace on string
  3. Convert string back to JSON using JSON.parse()

Using Object methods

You can also change the key to remove :: from it

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

Upvotes: 5

Related Questions