5
I have a string
in the following format:
"a=123 b="ABC" c="Olá Mundo!""
need to create a function that transforms this string in this json:
{
a : 123,
b : "ABC",
c : "Olá Mundo!"
}
I think it has a bit of regular expression and a split(), but I know almost nothing of Regex.
I was developing this function, but I wasn’t very successful.
function strToJson(str) {
var json = {};
var str_split = str.split(" ");
var str_split_value = [];
for (var i in str_split) {
str_split_value = str_split[i].split("=");
json[str_split_value[0]] = str_split_value[1];
}
return json;
}
console.log(strToJson('a=123 b="ABC" c="Olá Mundo!"'));
If you have something you tried, some beginning code? Or just the problem itself?
– MagicHat
My logic would be to split() the string separated by spaces, but this logic does not work very well in item c.
– Salomão Neto
Then, but starts something...and sees where it sticks, then edits the question and puts your code... Num leva a mal, mai then will have more answers... And they’ll help you solve...
– MagicHat
Calling a PHP function when user enters the page, some example?
– Alisson Hoepers
Although you have received a reply and are satisfied with it, this type of operation seems fundamentally problematic when using a data format without complete specification. Just to quote an example, what would happen if there were quotes inside a text? Before putting such code into production, always make sure it is not possible to write the data in a consistent format like JSON itself.
– utluiz
Of course I’m not going to put it into production, is that I’m very curious, and many of the questions I ask around here is just for knowledge.
– Salomão Neto