I have some object with map data and I need to convert it to JSON. I am using JSON.stringify() method, but after conversion I am getting next result:
{"someval":1,"someval2":"blabla","my_map":["{\"email\":\"[email protected]\",\"fullName\":\"username\"}"],"moredata":""}
I need to get clear string for my_map
, without extra '\' characters. How I can remove them? Just replace doesn't works because other values can have such characters.
I have some object with map data and I need to convert it to JSON. I am using JSON.stringify() method, but after conversion I am getting next result:
{"someval":1,"someval2":"blabla","my_map":["{\"email\":\"[email protected]\",\"fullName\":\"username\"}"],"moredata":""}
I need to get clear string for my_map
, without extra '\' characters. How I can remove them? Just replace doesn't works because other values can have such characters.
- You can use replace(regex) – Sirwan Afifi Commented Oct 14, 2017 at 13:10
- 2 @SirwanAfifi, that would break the JSON. – Mouser Commented Oct 14, 2017 at 13:13
- 1 No, do NOT use any sort of regex or replaced method. JSON processing should be done only by JSON methods – JAAulde Commented Oct 14, 2017 at 13:13
- 3 @SirwanAfifi that is a terrible suggestion – charlietfl Commented Oct 14, 2017 at 13:13
-
1
Why does it have to be a string? It’s very unusual to have a JSON string inside JSON. There isn’t really any benefit to do that.
my_map
should simply be an array containing an object, not a string. But if you really want it to be a string then the inner”
have to be escaped. There is no way around it. – Felix Kling Commented Oct 14, 2017 at 13:35
2 Answers
Reset to default 2I'm assuming my_map
is already JSON. To be exact I need to see the original map object, however the example below will provide enough insight to solve your problem with.
//correct example of a JavaScript object
var map = {"someval":1,"someval2":"blabla","my_map":[{"email":"[email protected]","fullName":"username"}],"moredata":""};
//also correct but the array content in my_map is a string and not treated as an object.
var map2 = {"someval":1,"someval2":"blabla","my_map":["{\"email\":\"[email protected]\",\"fullName\":\"username\"}"],"moredata":""};
console.log(JSON.stringify(map)); //correctly parsed
console.log(JSON.stringify(map2)); //incorrectly parsed
//solution for two:
//convert the string (JSON) to array and stringify result
map2["my_map"] = JSON.parse(map2["my_map"]);
console.log(JSON.stringify(map2));
You can use JSON.parse()
In this case my_map
contains an array which contains a string which needs to be JSON parsed. So to get the string you can do my_map[0]
. See example:
var x = {"someval":1,"someval2":"blabla","my_map":["{\"email\":\"[email protected]\",\"fullName\":\"username\"}"],"moredata":""};
var xx = JSON.parse(x.my_map[0]);
console.log('1: ' + xx.email);
console.log('2: ' + xx.fullName);