mapping deep json - javascript

How to mapping this json ?, i have been trying with multiple argument on each, but still can't get the data.
{
"data" : {
"after" : "t3_qp79c",
"before" : null,
"children" : [ {
"data" : { "url" : "http://imgur.com/c0COJ" },
"kind" : "t3"
} ],
"modhash" : ""
},
"kind" : "Listing"
}
My javascript code
$.getJSON(reddit_api_url,function(data) {
$.each(data.children['data'], function(i, reddit) {
// Uncomment line below to show tweet data in Fire Bug console
// Very helpful to find out what is available in the tweet objects
// console.log(reddit);
// Before we continue we check that we got data
console.log(i+' : '+ reddit );
// Build the html string for the current tweet
var tweet_html = reddit.url;
// Append html string to tweet_container div
$('#tweet_container').append(tweet_html);
});
}
Thanks

The data returned has its own data property, so you'd need...
data.data.children[0]['data']
...to get to that innermost data.
If you were iterating the children, then you'd pass that to $.each...
$.each(data.data.children, function(i, obj) {
console.log(obj.data.url);
});

Related

Firebase query DataSnapshot val() returning null

My Firebase structure is below
{
"Test1 Lab" : {
"Equipment" : "3-D printer",
"Hours" : "7AM-6PM",
"Location" : "Library",
"Name" : "Digital Lab"
},
"Test2 Lab" : {
"Equipment" : "Oculus",
"Hours" : "7AM-6PM",
"Location" : "Hall",
"Name" : "Test Lab"
}
}
The top level is called "makerspace". I am trying to get the Name, Equipment, and Hours of the item where the Location is "Library" I ran the code:
var red = database.ref('makerspace');
return red.orderByChild('Location').equalTo("Library").once('value').then(function(snapshot){
console.log(snapshot.child("makerspace").child("Name").key);
});
And I get "Name". However, when I change .key to .val(), I should expect to get "Digital Lab", but I get null. I don't know how to fix this.
The snapshot is already on the makerspace node, so it should be:
var red = database.ref('makerspace');
return red.orderByChild('Location').equalTo("Library").once('value').then(function(snapshot){
console.log(snapshot.child("Name").val());
});
Try this
var red = database.ref('makerspace');
return red.orderByChild('Location').equalTo("Library").once('value').then(function(snapshot){
snapshot.forEach(function(data) {
console.log(data.val());
});
});
I would recommend to access snapshot data like this,
red.orderByChild('Location').equalTo("Library").once('value').then(function(snapshot){
console.log(snapshot.val()); <==========
// result would be
{ "Test1 Lab" : { "Equipment" : "3-D printer","Hours" : "7AM-6PM","Location" : "Library","Name" : "Digital Lab" } }
}
To get properties you can do,
snapshot.val()['Test1 Lab']['Name'] or snapshot.val()['Test1 Lab'].Name
snapshot.val()['Test1 Lab']['Hours']
Now you can get 'Test1 Lab' using Object.keys(snapshot.val())[0]
snapshot.val() is like JSON Object, so just access its properties like you did for objects. No need to use child() method to access data.

How to retrieve the data from firebase JSON using JavaScript for each one of object

Here is my JSON and Code which gives only array but not it values. As I had used push it generating Unique Id from, which I am not getting. All the values that stored in that id.
{
"nitin" : [ {
"mobile" : {
"-K7GalDi5aAahDENCRi" : {
"name" : "file:///D:/Software%20Drive/addItem.html?category=mobile",
"price" : 345,
"quantity" : 34
}
},
"perfume" : {
"-K7K7HSu4rQNwbH3ud0H" : {
"name" : file:///D:/Software%20Drive/addItem.html?category=perfume",
"price" : 1000,
"quantity" : 20
}
}
}]
}
This is my code
fbref.on("value", function(snapshot) {
var newPost = snapshot.val();
console.log(newPost);
fbref.on("child_added", function(newPost,pre){
newchild=newPost.val();
console.log(newchild);
var n=newPost.key();
console.log("this is key"+n);
console.log("Name"+newchild.name);
console.log("Price"+newchild.price);
console.log("Quantity"+newchild.quantity);
});
});
The child_added event will fire when a child node is added directly under the location that you're querying.
So if you're querying the root of the JSON you show, a child_added will fire for nitin. And then if we'd add puf, a child_added will fire for that too.
{
"nitin" : [ {
...
}],
"puf": [ {
...
}],
}
If you want to receive a child_added for items inside mobile or perfume, you will need to attach a child_added on the parent node of those:
fbref.child('nitin').child(0).child('mobile').on('child_added'...
Or:
fbref.child('nitin/0/mobile').on('child_added'...
See this jsbin for a working sample of this.

Angular / Meteor: Array is undefined

I'm building an Angular / Meteor application, using Meteor's reactivity to populated an Angular model. It is all working fine until I start working with arrays.
// get sentence
$scope.sentence = $meteor.object(Sentences, $stateParams.sentenceId);
// related sentences
$scope.relatedSentences = $meteor.collection(function() {
return Sentences.find({_id: { $in: $scope.sentence.relatedSentences }});
});
I get this error on the JavaScript console
Error: $in needs an array
at Error (native)
at Object.ELEMENT_OPERATORS.$in.compileElementSelector (http://localhost:3000/packages/minimongo.js?af9eb9d7447544ca9b839a3dcf7ed2da2209b56c:1894:15)
at http://localhost:3000/packages/minimongo.js?af9eb9d7447544ca9b839a3dcf7ed2da2209b56c:1576:19
at Function._.each._.forEach (http://localhost:3000/packages/underscore.js? 0a80a8623e1b40b5df5a05582f288ddd586eaa18:164:22)
In the Mongo / Meteor console
meteor:PRIMARY> db.sentences.find({_id: "sp75iWPNqpbp2ypmy"});
{ "_id" : "sp75iWPNqpbp2ypmy", "sentence" : "Here is sentence 1 ", "language" : "en", "level" : "A1", "public" : true, "relatedSentences" : [ "wNs4ByDq7t396WLM3" ] }
And
meteor:PRIMARY> db.sentences.find({_id: { $in: [ "wNs4ByDq7t396WLM3" ] }});
{ "_id" : "wNs4ByDq7t396WLM3", "sentence" : "Here is sentence 0 ", "language" : "en", "level" : "A1", "public" : true, "relatedSentences" : [ ] }
I then commented out the failing find and have outputted the objects to html
$scope.sentence = $meteor.object(Sentences, $stateParams.sentenceId);
$scope.test = typeof $scope.sentence.relatedSentences;
Sentence: {{sentence}}<br/>
Related: {{sentence.relatedSentences}}<br/>
Typeof: {{test}}
Results
Sentence: {"autorunComputation": {"stopped":false,"invalidated":false,"firstRun":false,"_id":47,"_onInvalidateCallbacks": [null,null],"_parent":null,"_recomputing":false},"_id":"oFMp7swYyQsXkYsKz","sent ence":"Here is sentence 2","language":"en","level":"A1","public":true,"relatedSentences": ["wNs4ByDq7t396WLM3"]}
Related: ["wNs4ByDq7t396WLM3"]
Typeof: undefined
The Array is marked as undefined, but it is clearly shown in the full object. What am I missing?
EDIT
When running the above test on Firefox it returns an object
Related: ["wNs4ByDq7t396WLM3"]
Typeof: object
Related issue
$scope.test is only bound one time when this code initially runs. There is no data binding, so even if $scope.sentence.relatedSentences changes, test will not. The issue is that $scope.sentence.relatedSentences is populated asynchronously.
This would also apply to $scope.relatedSentences -- you are trying to set it initially before $scope.sentence.relatedSentences is available. You can use .subscribe on the value returned from .object to set this once the data is available.
$scope.sentence.subscribe().then(function () {
$scope.relatedSentences = $meteor.collection(function() {
return Sentences.find({_id: { $in: $scope.sentence.relatedSentences }});
});
});

How to get data from json in order to save them in database?

I am beginner in Javascript/jQuery and I am working on an interface made with KnockoutJS, so I have several models. I would like to save all the data in the database but I don't know how to do it.
I started with :
self.save = function() {
var data = ko.toJS(self);
var test = ko.toJSON(self);
console.log(test);
}
$.ajax({
url: "myURL",
data: {'carrier': data.carrier},
type: "POST",
});
and this is the result of the console.log :
{"id":1,"carrier":"1","Settings":[{"id":1,"price":{"id":1,"DeliveryStandard":"3.00","DeliveryExpress":"6.00","Details":{"id":1,"Standard":[{"id":1,"fromPrice":0,"maxPrice":"45.000"}],"Express"[{"id":1,"fromPrice":0,"maxPrice":"66.000"}]}}}}]}
I can get the value of carrier by using data.carrier but I don't know how to get the other data like DeiveryStandard, DeliveryExpress, fromPrice, maxPrice ...
Have you got an idea?
Thanks you in advance, and sorry if my question is silly!
If you format your JSON into a more readable format, with indenting, it makes it a lot easier to understand:
(though it should be noted that it is only technically JSON while in a string format, outside of that it is just a standard javascript object)
{
"id":1,
"carrier":"1",
"Settings":[
{
"id":1,
"price": { "id":1,
"DeliveryStandard":"3.00",
"DeliveryExpress":"6.00",
"Details": { "id":1,
"Standard": [{"id":1,
"fromPrice":0,
"maxPrice":"45.000"
}],
"Express" //Missing semi-colon
[{"id":1,
"fromPrice":0,
"maxPrice":"66.000"
}]
}
}
}}//One too many closing braces
]
}
First thing to note is you have 2 syntax errors, highlighted above with comments. So fix them first! (Though I wonder if they are typos as you seem to have it working at your end)
Then we can look at the structure tree to work out where the values you want are...
DeiveryStandard and DeliveryExpress are both properties of an object assigned to price, which it a property of the first item in the Settings array. So you can access them like so:
var DeliveryStandard = data.Settings[0].price.DeliveryStandard;
var DeliveryExpress= data.Settings[0].price.DeliveryExpress;
fromPrice and maxPrice are found multiple times, in both Standard and Express items. So you need to decide what version you need. If you want Standard then you can get the first item of the Standard array like so:
var standardObject = data.Settings[0].price.Details.Standard[0];
Which you can then access the properties of like:
var fromPrice = standardObject.fromPrice;
var maxPrice = standardObject.maxPrice;
I am sure you can work out how to get the Express version of the same data!
From what you seem to have been able to work out on your own, I think your problem is not knowing how to deal with the arrays. Note that arrays are defined with square brackets [], and elements within an array should be accessed with a zero-based index, for example: array[0] for the first element, and array[1] for the second element.
This should work.
console.log(data.Settings[0].price.DeliveryStandard);
Fixed some errors in your JSON.
var j = {
"id" : 1,
"carrier" : "1",
"Settings" : [{
"id" : 1,
"price" : {
"id" : 1,
"DeliveryStandard" : "3.00",
"DeliveryExpress" : "6.00",
"Details" : {
"id" : 1,
"Standard" : [
{
"id" : 1,
"fromPrice" : 0,
"maxPrice" : "45.000"
}
],
"Express": [
{
"id" : 1,
"fromPrice" : 0,
"maxPrice" : "66.000"
}
]
}
}
}
]
};
alert(j.Settings[0].price.DeliveryStandard);
alert(j.Settings[0].price.DeliveryExpress);
alert(j.Settings[0].price.Details.Standard[0].fromPrice);
alert(j.Settings[0].price.Details.Standard[0].maxPrice);

Construct JSON object from array on client-side?

I have a string array like this:
['QWJvdXQ=','SG93IGl0IFdvcmtz','SG9tZQ==','Q29udHJpYnV0ZQ==','Q29udGFjdA==']
What I want to do, is turn it into something like this:
[
{
"id" : "QWJvdXQ=",
"url": "about.html"
},
{
"id" : "SG93IGl0IFdvcmtz",
"url": "how_it_works.html"
},
{
"id" : "SG9tZQ==",
"url": "index.html"
},
{
"id" : "Q29udHJpYnV0ZQ==",
"url": "contribute.html"
},
{
"id" : "Q29udGFjdA=="
"url": "contact.html"
}
]
The attributes aren't the focus -- what I'm basically trying to do is make each item in the array an object with the value as an value of an attribute, and add another (or more) key-value pairs into those objects.
Right now, I'm trying to do this on the client-side, using jQuery and JS. I also am running node.js, so if this is easier to do on the server-side I'm open to any suggestions. Any help is appreciated!
What you need
JSON.stringify
Array.prototype.map
window.atob
all together;
JSON.stringify(
['QWJvdXQ=','SG93IGl0IFdvcmtz','SG9tZQ==','Q29udHJpYnV0ZQ==','Q29udGFjdA=='].map(
function (e) {
return {
'id': e,
'url': atob(e).toLowerCase().replace(/\s/g, '_') + '.html'
}; // I converted the string to URL as I expect you wanted
}
),
0, 4);

Categories

Resources