Applying JSON.parse() to unusual JSON file - javascript

Trying to access the value field of this JSON file using JSON.parse() in Meteor, but I cannot get it to return anything. I suspect there is an error in my syntax in selecting the data from the imported JS object.
{"status":"success","data":{"subjects":[{"value":"ABC","descr":"Descriptions"}]},"message":null,"meta":{"copyright":"Copyright","referenceDttm":"Date"}}
I'm trying to store it into an array, subjectArray. This is the code I'm using:
var subjectArray = new Array();
subjectFile = HTTP.get("https://classes.cornell.edu/api/2.0/config/subjects.json?roster=FA15");
subjectJSON = JSON.parse(subjectFile);
for (int i=0; i<subjectJSON.length; i++) {
subjectArray.push(subjectJSON[i].value)
}
Pretty printed this is:
{
"data": {
"subjects": [
{
"descr": "Descriptions",
"value": "ABC"
}
]
},
"message": null,
"meta": {
"copyright": "Copyright",
"referenceDttm": "Date"
},
"status": "success"
}

Responses from HTTP calls can take a while to come back so you should read your replies in an async way. You should move all of your code related to the "get" inside a callback function. If you want to find out more about HTTP and callbacks in Meteor make sure you check the docs
If you know what "value" is in your for loop ('cause I don't), then this is your answer:
HTTP.get("https://classes.cornell.edu/api/2.0/config/subjects.json?roster=FA15", function (err, res) {
if(!!err) return false;
subjectJSON = JSON.parse(res);
for (var i = 0; i < subjectJSON.length; i++) {
subjectArray.push(subjectJSON[i].value);
}
return true;
});
Also, there is no int in JavaScript.

Related

Limiting fields returned by mongo dynamically

I use Meteor to query a mongo collection. It has for example the following entry:
{
"_id": "uCfwxKXyZygcWQeiS",
"gameType": "foobar",
"state": "starting",
"hidden": {
"correctAnswer": "secret",
"someOtherStuff": "foobar"
},
"personal": {
"Y73uBhuDq2Bhk4d8W": {
"givenAnswer": "another secret",
},
"hQphob8s92gbEMXbY": {
"givenAnswer": "i have no clue"
}
}
}
What I am trying to do now is:
don't return the values behind "hidden"
from the "personal" embedded document only return the values for the asking user
In code it would look something like this:
Meteor.publish('game', function() {
this.related(function(user) {
var fields = {};
fields.hidden = 0;
fields.personal = 0;
fields['personal.' + this.userId] = 1;
return Games.find({}, {fields: fields});
}, Meteor.users.find(this.userId, {fields: {'profile.gameId': 1}}));
}
Obviously this won't work, because MongoDB won't allow mixed includes and excludes. On the other hand, I cannot switch to "specify only the included fields", because they can vary from gameType to gameType and it would become a large list.
I really hope that you can help me out of this. What can I do to solve the problem?
Typical example of where to use the directly controlled publication features (the this.added/removed/changed methods).
See the second example block a bit down the page at http://docs.meteor.com/api/pubsub.html#Meteor-publish.
With this pattern you get complete control of when and what to publish.

Rethinkdb multiple update by one query and conditional

How can I perfom multiple updates with one query and condition, using javascript ?
For example, my docs:
[
{
"Author": "Auto",
"Number": 5,
"RandomText": "dddbd",
"Tag": "Srebro",
"id": "10fbd309-5a7a-4cd4-ac68-c71d7a336498"
},
{
"Author": "Auto",
"Number": 8,
"RandomText": "cccac",
"Tag": "Srebro",
"id": "37f9694d-cde8-46bd-8581-e85515f8262f"
},
{
"Author": "Auto",
"Number": 6,
"RandomText": "fffaf",
"Tag": "Srebro",
"id": "b7559a48-a01a-4f26-89cf-35373bdbb411"
}
]
This is my query:
UpdateIndex()
{
this.r.table(this.params.table).update((row) => {
let result;
console.log(this.r.expr([row]));
this.r.branch(
this.r.row(this.Index2).lt(10),
result = "Lucky",
result = "Good"
);
/*
if(this.r.row("Number").lt(3)) result = "Bad";
else if (this.r.row("Number").lt(5)) result = "Poor";
else if (this.r.row("Number").lt(10)) result = "Lucky";
else if (this.r.row("Number").lt(20)) result = "Good";
else if (this.r.row("Number").lt(50)) result = "Great";
else result = "Mystic";
*/
console.log(result);
return this.r.object(this.Index2, result);
}).run(this.conn, this.CheckResult.bind(this));
}
Why I want to do this ? I created second index (this.Index2 = 'Opinion'), and now I would like to populate this index with values which are describe by my condition.
But every documents are the same values (example: Bad). How can I update documents, but run condition for every document, and with one query ?
Assigning to a local variable like that (result in your case) doesn't work with the way RethinkDB's driver builds up the query object to send to the server. When you write code like above, you're storing a literal string in the local variable once on the client (rather than once per row on the server) and then sending that literal to the server in the query you return at the bottom of your function. You also can't use console.log in the way you're trying to; that runs on the client, but your query is executed on the server. You may find http://rethinkdb.com/blog/lambda-functions/ useful for understanding what the client does with the anonymous functions you pass to commands like update.
You should use do for variable binding instead:
r.table(params.table).update(function(row) {
return r.branch(r.row(Index2).lt(10), "Lucky", "Good").do(function(res) {
return r.object(Index2, res);
});
})

Update JSON with jquery error

I'm trying to update a JSON file with the value of a textarea using jquery push. I'm receiving the following error: " JavaScript runtime error: Unable to get property 'push' of undefined or null reference"
My jquery:
function submittedMsg(ctx) {
var id = $('.msg-input form').attr('id');
var newMsg = $('.msg-input textarea').val();
var url = "/ajax.aspx?vtl=ajax-conversation-json&cv=" + id;
$.getJSON(url, function (messageString, message) {
var message = [];
message.push({
msgcontent: newMsg,
sendname: sendRname,
mbrhref: mbrUrl,
datetime: ""
});
});
}
My JSON:
{
"messageString" :
[
{ "subject": "hello",
"msgstring": "5",
"unread": "1",
"datetime": "Oct 1 2013 9:59PM",
"orderid": "17",
"recipient": [
{
"mbrname": "Jane Doe",
"mbrhref": "/profile.aspx?mem=1227"
},
{
"mbrname": "John Smith",
"mbrhref": "/profile.aspx?mem=1337"
}
],
"message": [
{
"datetime":"2013-10-01T21:59:33.063",
"sendname":"Jane Doe",
"mbrhref":"/profile.aspx?mem=1227",
"msgcontent": "<p>Hi. I would like to talk with you about Dwarf Beryl Beauty</p>"
},
{
"datetime":"2013-11-26T16:29:17.037",
"sendname":"John Smith",
"mbrhref":"/profile.aspx?mem=1337",
"msgcontent": "Tough luck."
}
]
}
]
}
I don't necessarily need to use push to update the JSON file if there is a better way, I'm open to suggestions. I've verified my URL path is correct. Am I just missing something obvious? I'm new to JSON and only have passable jquery skills. Help!
Thanks in advance for any direction.
Try to use:
data.message.push
instead of:
data.messageString.message.push
Ah I see the issue, you have a local var and parameter of the same name message:
$.getJSON(url, function (messageString, message) { //here is param message
var message = []; //here is a local var parameter
message.push({ //this is probably referencing the parameter which is not an array or object that supports .push
Instead:
$.getJSON(url, function (data) { //I renamed the param to be more consistent with documentation, although it doesn't really matter, just will generate confusion
data.messageString.push({ //modify the json we were passed in the data param

Add array key value in Javascript

I have a network array like the following way
"network_contents": [
{
"facebook":"contents to all pages",
},
{
"twitter":"twiter contents",
},
{
"linkedin":"linked in contents",
}
]
I would like to add some keys to that array bases on its content. If it is facebook the key should be facebook, if it is twitter key should be twitter. But not sure how to do it.
My requirement is to access network array contents, but it may or may not content these facebook, twitter, linked in values. I need to access its values. When i assign a key value will be easy to fetch its contents. So i tried this way to loop through the array
message.network_contents.forEach( function (nwContent) {
if(nwContent.twitter) {
console.log('nw content', nwContent.twitter);
}
})
can i create an array in this foreach loop like the following way.
{
"data": [
{
"facebook": {
"facebook": "facebook content"
},
"twitter": {
"twitter": "twitter content"
}
}
]
}
Your help is much appreciated thanks
Implementation of what I said in the comment:
var oldsies = stuff.network_contents;
var newsies = stuff.network_contents = {};
oldsies.forEach(function(network) {
var name = Object.keys(network)[0];
newsies[name] = network;
});
You gave an example of a JS object and not a dictionary and therefore cant add key-values.
You need something like this:
var network_contents = [];
network_contents["facebook"] = {config1: {name:"config1", value:"value1"}};
network_contents["twitter"] = {config2: {name:"config2", value:"value2"}};
example:
network_contents["facebook"].config1.value; // will return "value1"
You can covert your object to a dictionary easily.

The confuse about use jquery $.ajax to read javascript file

suppose I have a config javascript file:
window.Config = {};
Config.UI = {
"Area": {},
"Layer": {},
"Sprites": {},
"Audio": {}
};
Config.UI.Area = {
"prop": {
"uuid": {
"_type": "string",
},
"frame": {
"_type": "rect",
"_value": {
"x": "0",
},
"_aka": "frame"
},
"zIndex": {
"_type": "string",
}
},
then I want use $.ajax to read this file:
$.ajax({
url:'js/config.js',
success:function (data, textStatus) {
console.log(data);
}
})
the question is how can I get some key's value in the config,by use the data $.ajax return?
like the "Config.UI" or the 'uuid' in ui.area.prop?Or can I convert them to json?
Rather than use AJAX, why not just insert a script?
var script = $('<script>');
script.attr('type', 'text/javascript');
script.attr('src', 'js/config.js');
script.bind('load', function() {
// use window.Config
});
script.appendTo('head');
icktoofay has a good suggestion, and the issue with the jQuery.ajax call looks to be a missing dataType: 'script' option which will evaluate the response and should give you object access. You might want to look into jQuery.getscript() as well.
I find it very useful and powerful to store data on the server as javascript objects and read them using Ajax. And it is very easy to do. Let me give you an example from an educational application I have written.
This is an example table of contents file (l1contents.js) that I would store on the server:
{
title : "Lesson 1",
topics : [
{name : "Topic 1", file : "l1t1data.js" },
{name : "Topic 2", file : "l1t2data.js" },
]
}
This is the javascript code I use to process the file:
$.ajax({
url : contentsFileName, // would be set to 'l1contents.js'
dataType : 'text', // yes this is correct, I want jquery to think this is text
cache : false,
success: function(data) {
var contentsObj = eval('(' + data + ')');
var lessonTitle = contentsObj.title;
for (var i = 0; i < contentsObj.topics.length; i++) {
var topic = contentsObj.topics [i];
// process topic.name and topic.file here
}
}
});
Obviously, this is simplified, but hopefully you get the idea. I simply use eval to set the object. And note that I don't even need any javascript code defining the structure of contentsObj. (I, of course, do have extensive comments defining the structure of my objects, but they are simply comments, not code.)
if your json file contains json data than you can use parseJSON() , toJSON() method.
and another solution is use eval(), this conver json data to javascript object so you can easly get a value by giving key.

Categories