Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse map by JSON.stringify

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.

like image 606
Ted Avatar asked Mar 01 '26 16:03

Ted


1 Answers

I'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));
like image 102
Mouser Avatar answered Mar 03 '26 06:03

Mouser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!