Find the length of an JSON object - javascript

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.

Related

Parsing JSON keys into array of strings [duplicate]

This question already has answers here:
Get array of object's keys
(8 answers)
Closed 4 years ago.
I am currently trying to handle a GET request that returns a body in application/json structured like this:
{
"items": {
"item001": {"id":1234, "name": "name001"},
"item002": {"id":1235, "name": "name002"},
"item003": {"id":1236, "name": "name003"}
}
}
I'm trying to get an array of strings that looks like
array = ["item001", "item002", "item003"];
I don't care about any of the underlying hierarchy, I just need the key of each object as an array. I've tried several different methods (map(), JSON.stringify(), etc) but I can't seem to index each key in a array[i] format.
In fact, each time I try to even print the name of a single key, for example
var obj = JSON.parse({'whole json here'});
print(obj.items[1]);
I get an [object Object] error, which makes sense as obj.items is not indexed with a key other than "item001" for example. However, I do not know what the key for each object will be, hence the need for an array of the keys. Thank you in advance!
You can do Object.keys.It will return an array of the keys of an object
var x = {
"items": {
"item001": {
"id": 1234,
"name": "name001"
},
"item002": {
"id": 1235,
"name": "name002"
},
"item003": {
"id": 1236,
"name": "name003"
}
}
}
var y = Object.keys(x.items);
console.log(y)
You can use Object.keys(). For Reference
var obj={"items":{"item001":{"id":1234,"name":"name001"},"item002":{"id":1235,"name":"name002"},"item003":{"id":1236,"name":"name003"}}};
var result = Object.keys(obj.items);
console.log(result);
Object.keys will do that.
var obj = JSON.parse({'your json'});
console.log( Object.keys(obj.items) );

Is it possible to multiply values in JSON?

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.

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;

Reach into a JavaScript array object

If I console log test
I get
[
{
property_1: "a",
property_2: "b",
}
]
How can I console log the value of property_1 ?
console.log(test[0].property_1);
test is an array, who's first element is a map with keys property_1, and property_2.
test[0] accesses the first element of the array, which is a map. From there you can directly access the properties with the dot notation, or with a string subscript:
console.log(test[0]["property_1"]);
console.log(test[0]["property_1"])
First go into the array:
my_arr[0]
Then to get the property:
my_arr[0]['property_1']
End result:
var my_arr = [
{
property_1: "a",
property_2: "b",
}
]
alert(my_arr[0]['property_1']);
If that's what you get when you console.log, then I'd bet that you have a JSON string that needs to be parsed.
If so, do this...
var parsed = JSON.parse(test);
alert(parsed[0].property_1);

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