Is it possible to multiply values in JSON? - javascript

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
}

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.

Related

How to pass variable to JSON without printing it as String

How to pass variable to JSON object and print it like JSON object?
I simply want to pass variable value in JSON and print it like JSON which can also be used in console.table(obj)
With Stringify:
var name = "someName";
const json = JSON.stringify('{"result":'+name+', "count":42}');
const obj = JSON.parse(json);
console.log(obj);
Without stringify
var name = "someName";
const json = '{"result":'+name+', "count":42}';
const obj = JSON.parse(json);
console.log(obj);
Using \"variableName\" it gets value in \"...\" and not the variable value
var name = "someName";
const json = '{"result":\"name\", "count":42}';
const obj = JSON.parse(json);
console.log(obj);
Solution:
var debugJSON = [];
var section_number = 1;
var i = 25;
var x = section_number-i;
tempJSON = {
"section" : section_number,
"index" : i,
"fieldname" : x,
"isValid" : "not required"
};
debugJSON.push(tempJSON);
console.log(debugJSON);
//console.table(debugJSON); //Problematic on Chrome Browser and Stack Overflow
JSON is a text representation of some data structure.
Unless you write a JSON encoder (and you don't), you don't have any reason to produce JSON manually. Attempting to generate JSON using string concatenation fails if the variable strings (name in this case) contain quotes or backslash. Escaping them could produce valid results but the code becomes bloated and difficult to read without any gain.
JavaScript provides the method JSON.stringify() to produce a JSON from any data and this is the best way to generate JSONs.
All you have to do is to build the data structure that you need to encode. In your example, the data structure is an object:
let name = "someName";
const original = {
result: name,
count: 42,
}
// encode
const json = JSON.stringify(original);
console.log(json);
// decode
data = JSON.parse(json);
console.log(data);
Running the code snippet here in page is not relevant because the output that it produces looks similar for both calls of console.log().
Run the code using Node.js or run it in the browser's console to see the values of json (it is a string) and data (it is an object).
A JSON is quite literally a JavaScript object, so you don't treat it as a string, you work with objects, which you can later stringify if need be.
In your case, you don't want to pass a variable in a string, you should pass it in an object like so:
// Declaration of name
let name = 'someName';
// Create object and store name
const json = {
result: name,
count: 42
};
// Log object as JSON and as string
console.log(json);
console.log(JSON.stringify(json));
The first log returns your object as exactly that, an object, the second log, converts it into a string to do so as you please with it!

Parse json string array returned from c#

I am returning a JSON array string from c#, which is a list of classes I want to read county element in a class and add it to a js array. How can I parse this string?
{"d":"[{\"county\":\"PA\",\"state\":\"Mountur\"},{\"county\":\"PA\",\"state\":\" Beaver\"}]"}
The d property is itself JSON, so you need to parse that separately from the response to give you an array of objects which you can work with, something like this:
var response = {
"d": "[{\"county\":\"PA\",\"state\":\"Mountur\"},{\"county\":\"PA\",\"state\":\" Beaver\"}]"
}
var arr = JSON.parse(response.d);
arr.forEach(function(obj) {
console.log(obj.county + ' ' + obj.state);
});
console.log(arr);

Find the length of an JSON object

I have a JSON like the following.
How can I find the length of air in console,
console.log (block.number.path[i].air.length);
{ "block": [
{ "number": "36",
"path": [
{ "air": "[{\"name\":\"0\"},{\"name\":\"1\"},{\"name\":\"2\"}]" },
{ "water": "[{\"name\":\"3\"},{\"name\":\"4\"},{\"name\":\"5\"}]" },
{ "sand": "[{\"name\":\"6\"},{\"username\":\"7\"},{\"name\":\"8\"}]" }
]
}
]
}
air itself contains a JSON encoded array, which you have to decode first:
// your obj in here
var obj = { "..." : "..." };
// grab the respective length of the "air" attribute
var air = JSON.parse( obj.block[0].path[0].air );
console.log( air.length );
http://jsfiddle.net/pLAny/
You can solve this like so:
var length = JSON.parse(block.number.path[i].air).length;
console.log(length);
It kind of looks like some of that JSON got malformed. "air", "water", and "sand" are all JSON arrays...but parsed out into strings. If you're the one generating the JSON, look into that, because it doesn't seem right. As the other answers point out, it's still solvable in Javascript using JSON.parse(), as long as you can be sure your target browsers have that interface (most modern ones).
For any JSON array (anything declared using [] brackets) you can check its .length property.
Given that json is a variable containing your JSON, you can do:
json["block"][0]["path"][0]["air"].length
Block is an array, so you have to access to the element first:
a.block[0].path[0].air.length
where a is the variable where you are holding the data.

Passing a external variable in JSON.parse function

I am trying to get a value from json by using the JSON.parse function. My json response is given below:
{
"rows": 10,
"os": "0",
"page": "1",
"total": "122",
"projects": {
"P143841": {
"id": "P143841",
"locations": [{
"geoLocId": "0002220957",
"latitude": "3.866667",
"longitude": "11.516667"
}],
}
}
}
I am able to get the value 10 if I do JSON.parse(obj.rows) but if I assign the rows to a variable say var value = rows and then I pass it to the JSON.parse(obj.value) function I got undefined.
P.S. I won't be knowing the names of the response parameters, i.e. i won't know if it will be rows or os quoting from the above example. I will be retrieving them from a database. If I perform the code below:
for (var i=0;i<length;i++) {
var value = responseParam_array[i];
console.log(obj.value);
}
I get the output but any help will be much appreciated.
As per the other answers you shouldn't need to parse individual properties, just parse the original JSON and then operate on the resulting object.
But as for this problem:
"if I assign the rows to a variable say var value = rows and then I pass it to the JSON.parse(obj.value) function I got undefined"
If value is a variable holding the name of a property of obj then you need:
obj[value]
// NOT
obj.value
When you use "dot" notation the part on the right of the dot is taken as the literal name of the property, not as a variable. Using the square-bracket syntax the expression in the brackets is evaluated and its result is taken as the property name.
you should be json-parsing your whole object and using the parsed object afterwards (you dont need to parse every property for itself)
var strObj = '{"rows": 10,"os": "0","page": "1","total": "122","projects":{"P143841":{"id":"P143841",}}';
var obj = JSON.parse(strObj);
var rows = obj.rows;
If I understand your question:
var str = '{ "some": "JSON String like the one above with", "rows": 10 }';
var parsed = JSON.parse(str);
var whatYouWant = parsed.rows;

Get a certain value from a json object

I have a json object
eg
{
"href":"Test",
"commentID":"12334556778"
}
Is there a way just to get the second line i.e. "commentID":"12334556778"
I'm using
JSON.stringify(json)
Thanks all
You can create another object containing only the commentID property:
var obj = {
"href": "Test",
"commentID": "12334556778"
};
var result = JSON.stringify({
"commentID": obj.commentID
});
JSON.stringify accepts a third argument which handles white-space in the output. If the third argument is present and "truthy", line-breaks will be inserted and each level will be indented using the argument's string value, or a number of spaces if a number is passed. Using this technique, you can get the browser to insert line-breaks and then split on those line-breaks in the result:
var obj = {
"href":"Test",
"commentID":"12334556778"
},
arr = JSON.stringify(obj, null, 1).split("\n");
alert(arr[2]);
//-> ' "commentID": "12334556778"'
Working demo: http://jsfiddle.net/AndyE/ercRS/ (requires browsers with JSON/trim)
You might want to trim any leading white space or trailing comma, but I'll leave that up to you.
if you have a JSON object at hand, just use it like you would use an array.
var jsonObject = {
"href":"Test",
"commentID":"12334556778"
}
alert(jsonObject['commentID']); // alerts 123445678
JSON.stringify() is used if you want to send the data back to your server.

Categories