I have this code:
let test = '{"attribute_as":"plan_id","operator":"fromTo","values":"{"from":"70","to":"80"}"}';
console.log(JSON.parse(test));
It of course fail because in values
I have an object. Is there any option how to parse this string in easy way? Or is it not possible at all?
At the end the result should be:
{
attribute_as: 'plan_id',
operator: 'fromTo',
values: {
from: 70,
to: 80
}
}
CodePudding user response:
The string is incorrect:
let err = '{"attribute_as":"plan_id","operator":"fromTo","values":"{"from":"70","to":"80"}"}';
// This is the original string
let pass = '{"attribute_as":"plan_id","operator":"fromTo","values":{"from":70,"to":80}}';
// Corrected string
let desiredObj = {
attribute_as: 'plan_id',
operator: 'fromTo',
values: {
from: 70,
to: 80
}
};
console.log(JSON.stringify(desiredObj) == err);
console.log(JSON.stringify(desiredObj) == pass);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
This should do the trick. When logged both evaluated correctly.
let
test = '{"attribute_as": "plan_id","operator": "fromTo","values": {"from": 70,"to": 80}}',
test2 = {
attribute_as: 'plan_id',
operator: 'fromTo',
values: {
from: 70,
to: 80
}
}
console.log(JSON.parse(test));
console.log(JSON.stringify(test2));