Find length of json string - javascript

I have following Jsonstring
var j = { "name": "John" };
alert(j.length);
it alerts : undefined, How can i find the length of json Array object??
Thanks

Lets start with the json string:
var jsonString = '{"name":"John"}';
you can easily determine its length:
alert("The string has "+jsonString.length+" characters"); // will alert 15
Then parse it to an object:
var jsonObject = JSON.parse(jsonString);
A JavaScript Object is not an Array and has no length. If you want to know how many properties it has, you will need to count them:
var propertyNames = Object.keys(jsonObject);
alert("There are "+propertyNames.length+" properties in the object"); // will alert 1
If Object.keys, the function to get an Array with the (own) property names from an Object, is not available in your environment (older browsers etc.), you will need to count manually:
var props = 0;
for (var key in jsonObject) {
// if (j.hasOwnProperty(k))
/* is only needed when your object would inherit other enumerable
properties from a prototype object */
props++;
}
alert("Iterated over "+props+" properties"); // will alert 1

Another way of doing this is to use the later JSON.stringify method which will give you an object (a string) on which you can use the length property:
var x = JSON.stringify({ "name" : "John" });
alert(x.length);
Working Example

function getObjectSize(o) {
var c = 0;
for (var k in o)
if (o.hasOwnProperty(k)) ++c;
return c;
}
var j = { "name": "John" };
alert(getObjectSize(j)); // 1

There is no json Array object in javascrit. j is just an object in javascript.
If you means the number of properties the object has(exclude the prototype's), you could count it by the below way:
var length = 0;
for (var k in j) {
if (j.hasOwnProperty(k)) {
length++;
}
}
alert(length);

An alternate in Jquery:
var myObject = {"jsonObj" : [
{
"content" : [
{"name" : "John"},
]
}
]
}
$.each(myObject.jsonObj, function() {
alert(this.content.length);
});
DEMO

Related

Convert a JSON Object to Comma Sepearted values in javascript

I have a JSON OBJECT
{"data":{"source1":"source1val","source2":"source2val"}}
which i want to convert into
data : source1val, source2val.
Use Object.keys with Array#map
The Object.keys() method returns an array of a given object's own enumerable properties.
The map() method creates a new array with the results of calling a provided function on every element in this array.
var input = {
"data": {
"source1": "source1val",
"source2": "source2val"
}
};
var output = Object.keys(input.data).map(function(k) {
return input.data[k];
}).join(',');
console.log(output); //manipulated object
console.log(input); //Original object
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
var input = {
"data": {
"source1": "source1val",
"source2": "source2val"
}
};
var output = [];
var i;
for (i = 0; i < input.data.length; i++) {
output.push(input.data[i]);
}

Javascript, retrieve array name

I have this:
var one = ['12','24','36'];
var two = ['10','20','30'];
If I do:
alert(one) I have: 12,24,36. And it's ok.
I need to have the name of the array from another function, where I call it from a for like this:
var test = [one,two]
for (i = 0; i < test.length; i++) {
alert(test[i]);
}
I have "12,24,36" and then "10,20,30" in the alert, but I need the name of the array, not the content. How to do?
I want two alert with: "one" and "two", the name of Array.
Use an object to hold your arrays:
var obj = {
one: ['12','24','36'],
two: ['10','20','30']
}
for (var p in obj) {
console.log(p); // log the key
}
Alternatively you can use Object.keys(obj) to retrieve an array of the object keys.
And if you need to log the array contents:
for (var p in obj) {
console.log(obj[p]); // log the array contents
}
DEMO
Yes, I agree with elad.chen. You can try something like:
var objects = [
{name:"one",value:['12','24','36']},
{name:"two",value:['12','24','36']}
];
for(var i=0;i<objects.length;i++){
console.log(objects[i].name);
console.log(objects[i].value);
}
You can use an "Object Literal" and use the property name as the name, and the value as the array..
For example:
var arrays = {
"one": [1,2,3],
"two": [1,2,3]
}
for ( var k in arrays ) {
alert('"Array name" = ' + k)
alert('"Array value" = ' + arrays[k].toString() )
}
At some place, the name must be set. While Javascript is can add properties to objects, this can be used for a name property without changing the behaviour of the arrays.
var one = ['12', '24', '36'];
one.name = 'one';
var two = ['10', '20', '30'];
two.name = 'two';
var test = [one, two], i;
for (i in test) {
document.write(test[i].name + '<br>');
}

How to count the number of arrays nested within a JavaScript object by name

I have a generic function that needs to check the number of items in the array that is named, but I don't always know what the name is going to be called. Is there a way to do this?
array:
// added array example here per request:
var myArray = { "name": "myname", "data": [ "item1": [1], "item2": [2,3,4,5,6,7,8,9], "item3": [41,42,51,491]}
// where length is the number of objects in the array.
var mycount = someitem.getProperty("UnknownName").length;
what I want to do is call some function that does this:
var mycount = specialCountFunction(someitem, name);
In your specialCountFunction(), receive the property name as a string, and then use square brackets after item to evaluate the value of the string in order to use it as a property name.
function specialCountFunction(item, name) {
return item[name].length;
}
So then you'd call it like this:
var name = "whatever_the_name_is";
var count = specialCountFunction(someitem, name);
Do you mean to get the length of an array in an object?
For example, your object
var obj = {
"children": [ "john", "mark", "sam" ]
}
Get the length with obj["children"].length
Or the length of an object ?
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
// Get the size of an object
var size = Object.size(obj);

Get number of rows of multidimensional JSON variable

I have a PHP function that returns a multiple-level JSON object in the format
var data = {
1 : {
1: { Object },
2: { Object },
...,
...
},
2: {
1: { Object },
2: { Object },
...,
...
}
}
I need to get the length of data to initialize a for loop maximum value. By this, I mean the count of the first level entries.
data[1].length returns 22, and data[2].length returns 23 via the console.log printout. This is expected, but data.length returns undefined.
Is there a better method than
var count = 0;
for (var i=1; i< Number.MAX_VALUE; i++){
if (typeof data[i] != 'undefined')
count = i;
}
How About
Object.keys(data).length
If you can control the JSON format, nested arrays seem a better alternative.
If not, you can run something like
var length = 0;
for (var i in data) {
if (isFinite(i) && i > length)
length = i;
}
You can count the number of entries in a loop, like this:
var length = 0;
for (var key in data) {
if (data.hasOwnProperty(key)) {
length++;
}
}
However, if you have control over the returned data, it would probably be easier to return an array instead of an object because the array will already have the length property you want.
Why not just do this instead of assigning numeric properties? Arrays will have the length property you wish:
var data = [
[
{ Object },
{ Object },
...,
...
],
[
{ Object },
{ Object },
...,
...
]
]

Sort complex JSON based on particular key

I have a JSON object with the following format:
{
items:{
nestedObj:{
position:3
},
nestedObj2:{
position:1
},
nestedObj3:{
position:2,
items:{
dblNestedObj:{
position:2
},
dblNestedObj2:{
position:3
},
dblNestedObj3:{
position:1
}
}
}
}
}
I am attempting to sort each level of nested object by their position attribute. I can recursively iterate the object, but I don't know where to start for sorting it...
Unfortunately it's not quite so easy to use the sort method as it would if you had an array. So let's build an array:
var tmp = [], x;
for( x in obj.items) { // assuming your main object is called obj
tmp.push([x,obj.items[x].position]);
// here we add a pair to the array, holding the key and the value
}
// now we can use sort()
tmp.sort(function(a,b) {return a[1]-b[1];}); // sort by the value
// and now apply the sort order to the object
var neworder = {}, l = tmp.length, i;
for( i=0; i<l; i++) neworder[tmp[i][0]] = obj.items[tmp[i][0]];
obj.items = neworder;

Categories

Resources