Print contents of JSON Object - javascript

I have an object in which I used JSON Stringify with to view its contents like so:
var testing = JSON.stringify($scope.test, null, 4);
And the object looks like this when i do console.log(testing):
{
"_id": "53e866a8a595b7041f9510c9",
"start": "2014-08-04T07:00:00.000Z",
"end": "2014-08-16T07:00:00.000Z",
"location": "Australia",
"name": "Joe's Surprise",
"__v": 1,
"array": [
{
"_id": "53ddc8c98ae4813c0420e189",
"provider": "local",
"name": "Test User",
"username": "testUser",
"email": "test#test.com",
"hashedPassword": "e5ri7OVhzNQMZpSqxnB3p2FyrpxskFE3yM8jHn5hfzZZvdd57YhhJrjFWJqBQhhyZz6y8UG68mr+rQ95admtfw==",
"salt": "PVEFtMfyJ/7TX9Do0cYMdQ==",
"__v": 2,
"attending": [
"53e866a8a595b7041f9510c9"
],
"role": "user"
},
]
}
however, I want to print out the username attribute within the array attribute of variable testing but I am unable to do so. I've tried doing a for loop like so:
for(var i = 0; i < testing.array.length; i++){
console.log(testing.array[i].username);
}
But the .length attribute is considered undefined. I've also tried simply doing console.log(testing._id) to see if that works but this returns undefined. I'm not sure what I'm doing wrong, can anyone help? Thanks!

var testing = JSON.stringify($scope.test, null, 4);
is converting $scope.test into a string (presumably so you can view in a human readible format). A string contains no arrays or properties. You want it in its original form, not in a string.
you probably want:
for(var i = 0; i < $scope.test.array.length; i++){
console.log($scope.test.array[i].username);
}

Related

Adding data to JSON array

I have a JSON Array inside my Node.js code with the following schema:
{
"status": "ok",
"data": [
{
"id": 1,
"active": true,
"createdAt": "2017-07-21T15:39:31.000Z",
"updatedAt": "2017-07-21T15:47:13.000Z"
}
]
}
and I want to add data so it will look like:
{
"status": "ok",
"data": [
{
"id": 1,
"active": true,
"createdAt": "2017-07-21T15:39:31.000Z",
"updatedAt": "2017-07-21T15:47:13.000Z",
"information": "someInformation"
}
]
}
Can you help me how to do this?
Thanks!
Like this? access the data property, of the obj variable, and the first element in that array, then set a new property on that object equal to your string.
var obj = {
"status": "ok",
"data": [
{
"id": 1,
"active": true,
"createdAt": "2017-07-21T15:39:31.000Z",
"updatedAt": "2017-07-21T15:47:13.000Z"
}
]
};
obj.data[0].information = "someInformation";
console.log( obj );
Since you have already the JSON you should firstly parse it, because JSON is a string. After parsing you will get object that should be saved in some variable, then you can access it as general object and add the property you want. Then you have to transform it to JSON string again. It will be like this
var parsed = JSON.parse(data); // Now we are transforming JSON string into the object
//Now you may do whatever you want
parsed.newprop = 'some text';
parsed.hello = 'Hellow world';
data = JSON.stringify(parsed); // Now we are replacing the previous version of JSON string to new version with additional properties
var dataContainer = {
"status": "ok",
"data": [
{
"id": 1,
"active": true,
"createdAt": "2017-07-21T15:39:31.000Z",
"updatedAt": "2017-07-21T15:47:13.000Z"
}
]
};
for(var i = 0; i < dataContainer.data.length; i++) {
dataContainer['data'][i]['information'] = "some information";
}
Hope it helps you !

How to get specific array from JSON object with Javascript?

I am working with facebook JS SDK which returns user's information in JSON format. I know how to get the response like response.email which returns email address. But how to get an element from a nested array object? Example: user's education history may contain multiple arrays and each array will have an element such as "name" of "school". I want to get the element from the last array of an object.
This is a sample JSON I got:-
"education": [
{
"school": {
"id": "162285817180560",
"name": "Jhenaidah** School"
},
"type": "H**hool",
"year": {
"id": "14404**5610606",
"name": "2011"
},
"id": "855**14449421"
},
{
"concentration": [
{
"id": "15158**968",
"name": "Sof**ering"
},
{
"id": "20179020**7859",
"name": "Dig**ty"
}
],
"school": {
"id": "10827**27428",
"name": "Univer**g"
},
"type": "College",
"id": "9885**826013"
},
{
"concentration": [
{
"id": "108196**810",
"name": "Science"
}
],
"school": {
"id": "2772**996993",
"name": "some COLLEGE NAME I WANT TO GET"
},
"type": "College",
"year": {
"id": "1388*****",
"name": "2013"
},
"id": "8811215**16"
}]
Let's say I want to get "name": "some COLLEGE NAME I WANT TO GET" from the last array. How to do that with Javascript? I hope I could explain my problem. Thank you
Here is a JsFiddle Example
var json = '{}' // your data;
// convert to javascript object:
var obj = JSON.parse(json);
// get last item in array:
var last = obj.education[obj.education.length - 1].school.name;
// result: some COLLEGE NAME I WANT TO GET
If your json above was saved to an object called json, you could access the school name "some COLLEGE NAME I WANT TO GET" with the following:
json.education[2].school.name
If you know where that element is, then you can just select it as already mentioned by calling
var obj = FACEBOOK_ACTION;
obj.education[2].school.name
If you want to select specifically the last element, then use something like this:
obj.education[ obj.education.length - 1 ].scool.name
Try this,
if (myData.hasOwnProperty('merchant_id')) {
// do something here
}
where JSON myData is:
{
amount: "10.00",
email: "someone#example.com",
merchant_id: "123",
mobile_no: "9874563210",
order_id: "123456",
passkey: "1234"
}
This is a simple example for your understanding. In your scenario of nested objects, loop over your JSON data and use hasOwnProperty to check if key name exists.

How to get an array inside an array?

Hi I have trouble with an array response of json.
I'm supposed to get the members of the objects. but that array is inside another array.
This is the array that is being returned.
var arr = [
[
{
"id": 4243430853,
"email": "jayduco2#gmail.com",
},
{
"id": 4227666181,
"email": "deofederickduran#gmail.com",
},
{
"id": 4227644293,
"email": "kfsucayan#gmail.com",
}
],
[
{
"id": 4243430854,
"email": "jayduco2#gmail.com",
},
{
"id": 4227666182,
"email": "deofederickduran#gmail.com",
},
{
"id": 4227644294,
"email": "kfsucayan#gmail.com",
}
]
];
How can i dig down to the values? before I would use arr[i].email, but now it doesn't work. I've tried arr[0].[i].email, but returns be the error missing name after . operator. Is there a way that I can remove that outer array?
It should be arr[i][j].email. i to loop over the array arr itself and j to loop over each sub-array.
arr[i] will give you something like this (if i == 0 for example):
[
{
"id": 4243430853,
"email": "jayduco2#gmail.com",
},
{
"id": 4227666181,
"email": "deofederickduran#gmail.com",
},
{
"id": 4227644293,
"email": "kfsucayan#gmail.com",
}
]
and then arr[i][j] will give something like this (if i == 0 and j == 2):
{
"id": 4227644293,
"email": "kfsucayan#gmail.com",
}
then you can access the email property using arr[i][j].email.
There's two ways to access objects in Javascript: using periods or using square brackets. Here, you're trying to mix the two, which works, but probably isn't the best practice. You should pick whichever is best for the situation. Here, you'd want to use the brackets:
arr[i][j]["email"];
Note that when using variables, you will always need to use brackets as opposed to periods.

How can I do a multidimensional search with JSON in Javascript?

I am trying to write a basic, experimental search system using JavaScript and JSON, with the searchable data contained in the JSON file. Multiple 'posts' are listed in the file, and each post has an array of 'tags'. My intent is to search through each posts tags, and retrieve only the posts that have tags matching a query, such as "funny cat video" (the posts would have to have all three tags, "funny", "cat", and "video", to be returned).
My particular concern is performance. I am sure that this technique will be inefficient, as there are approximately 2000 posts, and each one has from 5 to 50 tags, but it has to be done with JavaScript. I am already referencing from this website on how to maximise performance, though I could do with some extra help.
Here is my code so far for storing the data:
{
"index": {
"count": "2",
"posts": [
{
"id": "1",
"date": "2014-11-21 17:16:39 GMT",
"url": "http://url/",
"image": "http://big_image/",
"thumbnail": "http://little_image/",
"tags": ["funny", "cat", "picture", "falling", "chair", "window sill", "funny"]
},
{
"id": "2",
"date": "2014-11-20 17:57:32 GMT",
"url": "http://url1/",
"image": "http://big_image1/",
"thumbnail": "http://little_image1/",
"tags": ["funny", "cat", "picture", "jumping", "water", "bath", "funny"]
}
]
}
}
And this is my Javascript:
var query = "funny cat bath".split(" ");
var data = JSON.parse("THE JSON GOES HERE");
var count = data.index.count;
var index = data.index.posts;
for (var i = 0, indexLength = index.length; i < indexLength; i++) {
tags = index[i].tags;
for (var q = 0, queryLength = query.length; q < queryLength; q++) {
if(tags.indexOf(query[q]) !== false) {
console.log(index[i]);
}
}
}
Unfortunately, I can't figure out how to get it to return only the posts that have all three tags, and it returns all posts with any of the tags supplied. Not only that, but it returns duplicates.
Does anybody have a better solution? I'm stuck.
You need to use a flag and only "write" out the match when they are all found, you are writing it out when one is found. Plus indexOf returns -1, not false. Basic idea below:
var data = {
"index": {
"count": "2",
"posts": [
{
"id": "1",
"date": "2014-11-21 17:16:39 GMT",
"url": "http://url/",
"image": "http://big_image/",
"thumbnail": "http://little_image/",
"tags": ["funny", "cat", "picture", "falling", "chair", "window sill", "funny"]
},
{
"id": "2",
"date": "2014-11-20 17:57:32 GMT",
"url": "http://url1/",
"image": "http://big_image1/",
"thumbnail": "http://little_image1/",
"tags": ["funny", "cat", "picture", "jumping", "water", "bath", "funny"]
}
]
}
};
var query = "funny cat bath".split(" ");
var filteredSet = []; //where the matched objects will reside
var posts = data.index.posts; //get the posts
for (var i=0; i<posts.length;i++) { //loop through the posts
var post = posts[i];
var tags = post.tags; //reference the tags
var hasMatch = true; //flag to hold the state if we have a good match - set to true by default
for (var j=0; j<query.length; j++) { //loop through the tags the user is looking for
var index = tags.indexOf(query[j]); //look for it in the set [Note older IEs needs polyfill see MDN for code]
if (index===-1) { //indexOf returns -1 if not found
hasMatch=false; //set Boolean flag so we do not record item
break; //exit loop - no reason to keep checking
}
}
if (hasMatch) { //if we found all the tags
filteredSet.push(post); // add to the filtered set
}
}
console.log(filteredSet); //show the filtered set

Reading JSON data for a particular ID

I have some JSON data which is in the following format:
[
{
"id": 145,
"Name": "John",
"company_name": "A",
"email": "john#gmail.com",
"country": "USA"
},
{
"id": 500,
"Name": "Mike",
"company_name": "B",
"email": "mike#gmail.com",
"country": "London"
},
{
"id": 100,
"Name": "Sally",
"company_name": "C",
"email": "sally#gmail.com",
"country": "USA"
}
]
Now, suppose I ask the user to enter an id, say 100. Then I need to display all the details for this id.
I am supposed to do this as a part of a web application,where I have to invoke an display the fields of a particular id. This would have been easy if I had a hash like implementation and could display all parameters based on the key-id.
Can anybody tell me how this can be done using such kind of data?
Thanks!
You could use something like this:
(Assuming the you have a variable data with your Json Object).
function getid(id) {
var nobj;
data.forEach(function(obj) {
if(obj.id == id)
nobj = obj;
});
return nobj
}
var neededobj = getid(100);
console.log(neededobj.Name + "\n" + neededobj.email + "\netc...");
But to get the Object you have to loop through your complete array,
until it finds the right Object
see this Fiddle
I think you are looking for Associative Array,
the simplex one would be,
var associativeArray = [];
associativeArray["one"] = "First";
associativeArray["two"] = "Second";
associativeArray["three"] = "Third";
alert(associativeArray.one);
And obviusly you can add json object in value place

Categories