Is it valid in JSON to set value of key as the result of multiplaying/adding two variables/values/string+number/string+string/etc.?Is it possible?
F.e
{
"string": "600*"+40
}
Is it valid in JSON to set value of key as the result of multiplaying/adding two variables/values/string+number/string+string/etc.?Is it possible?
F.e
{
"string": "600*"+40
}
Share
asked Jul 11, 2017 at 18:18
PatlatuiPatlatui
111 silver badge1 bronze badge
4
-
3
you could provide a function, I believe. like
{"string": function(){return 600*40} }
– blurfus Commented Jul 11, 2017 at 18:20 - 5 @ochi not if it is really JSON – charlietfl Commented Jul 11, 2017 at 18:21
- @charlietfl you are correct! Strictly speaking, JSON does not allow it – blurfus Commented Jul 11, 2017 at 18:26
- 2 What is the real problem you are trying to solve? XY-problem – Yury Tarabanko Commented Jul 11, 2017 at 18:27
3 Answers
Reset to default 8JSON isn't code. It's not JavaScript. It's just a format for writing data. It can't do anything dynamically.
If you wanted to do something like that, you'd have to do it with whatever is creating the JSON.
With JavaScript, you can do something like this:
const jsonStr = '{ "value": 600 }'; // load your JSON from somewhere
const data = JSON.parse(jsonStr); // parse JSON
data.value *= 40; // do stuff
console.log(JSON.stringify(data)); // turn back into JSON.
Note, if it was something like { "value": "600" }
where the value is a string, not a number (note the quotation marks (""
)), you'd have to remember to parseInt
first: data.value = parseInt(data.value) * 40
In short, no. You can't multiply Strings and JSON means that it's a string representation of a Javascript Object.
I think you can save it this way
{
"string": "600+40"
}
or
{
"string": "600*40"
}
but it will only be string. If you want to do math on it you have to convert it.