最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Is it possible to multiply values in JSON? - Stack Overflow

matteradmin4PV0评论

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
Add a ment  | 

3 Answers 3

Reset to default 8

JSON 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.

Post a comment

comment list (0)

  1. No comments so far