Javascript parse query - javascript

I'm having trouble with the following query. I'm pretty sure all the keys are right but the query isn't returning any objects. The problem line is:
query.equalTo("author", Parse.User.current());
If I take that line out then it returns me a random user's object, but I want this user's object. if I leave that line in I get no objects.
var query = new Parse.Query("personalInfoObject");
console.log(Parse.User.current().getUsername());
query.equalTo("author", Parse.User.current());
query.find({
success: function(results) {
// results is an array of Parse.Object
var obj=results[0];
console.log(obj)
},

User looks like a complex object. If author is a simple string, that comparison won't find anything. I see that you're printing out the username to the log, perhaps that's what you want to use for the where clause. It's hard to know without the structure of the objects.

Related

Javascript object with arrays to search param style query string

Looking for clean way to convert a javascript object containing arrays as values to a search param compatible query string. Serializing an element from each array before moving to the next index.
Using libraries such as querystring or qs, converts the object just fine, but handles each array independently. Passing the resulting string to the server (which I cannot change) causes an error in handling of the items as each previous value is overwritten by the next. Using any kind of array notation in the query string is not supported. The only option I have not tried is a custom sort function, but seems like it would be worse than writing a custom function to parse the object. Any revision to the object that would generate the expected result is welcome as well.
var qs = require("qs")
var jsobj = {
origString:['abc','123'],
newString:['abcd','1234'],
action:'compare'
}
qs.stringify(jsobj,{encode:false})
qs.stringify(jsobj,{encode:false,indices:false})
qs.stringify(jsobj,{encode:false,indices:false,arrayFormat:'repeat'})
Result returned is
"origString=abc&origString=123&newString=abcd&newString=1234&action=compare"
Result desired would be
"origString=abc&newString=abcd&origString=123&newString=1234&action=compare"
I tried reorder your json:
> var jsobj = [{origString: 'abc', newString: 'abcd' }, {origString: '123',
newString: '1234' }, {action:'compare'}]
> qs.stringify(jsobj,{encode:false})
'0[origString]=abc&0[newString]=abcd&1[origString]=123&1[newString]=1234&2[action]=compare'
But I don't know if this is a good alternative for your problem.
Chalk this up to misunderstanding of the application. After spending some more time with the API I realized my mistake, and as posted above by others, order does no matter. Not sure why my first several attempts failed but the question is 'answered'

Json Keys Are Undefined When Using Them From Script Tag

I've been trying to load certain Json with Ajax GET request and then parsing it.
However when trying to access the Json key from HTML script tag it was undefined.
In order to debug this issue, I logged all the keys of Json in console as well as the Json itself. Therefore i utilized this function:
function getInv() {
$.get( "/inventory/", function( data ) {
var invList = data.split(",, "); // Explanation is below
console.log(invList[0]) // Just testing with first object
console.log(Object.keys(invList[0]));
});
}
getInv();
Purpose of data.split(",, "):
Since my backend script uses different programming language, I had to interpret it to the one suitable for Javascript.
There also were multiple Json objects, So i separated them with ",, " and then split them in Javascript in order to create a list of Json objects.
After calling the function, Following output was present:
Although the interesting part is that after pasting Json object in console like this:
This was the output:
So basically, in script tag, i was unable to access object's keys, although once i used it manually in console, all keys could be accessed.
What could be the purpose behind this? It seems quite strange that different outputs are given. Perhaps invList[0] is not Json object at all in the script tag? Thanks!
data.split() returns an array of strings, not objects. You need to use JSON.parse() to parse the JSON string to the corresponding objects.
function getInv() {
$.get( "/inventory/", function( data ) {
var invList = data.split(",, ");
console.log(invList[0]) // Just testing with first object
var obj = JSON.parse(invList[0]);
console.log(Object.keys(obj));
});
}
You can use .map() to parse all of them, then you'll get an array of objects like you were expecting:
var invList = data.split(",, ").map(JSON.parse);

Get specific object from Parse (.com) query result by field without going back to DB

So say I do a query on Parse database and get a results object, with each result having a field place_id.
How can I then get a specific object by place_id from the results without actually going back to the database (want to minimise network traffic and db querying...)?
This is what my query will look like:
var LatestUpdate = Parse.Object.extend("LatestUpdate");
var query = new Parse.Query(LatestUpdate);
query.containedIn("place_id", arrayOfplaceIds);
query.find().then(
function(results){
// and then i want to do something like:
return results.findByField("place_id", 1234) // get a specific object from the result without going back to the database?
}
);
You have to loop through your results and find the object that matches your criteria. You can do this easily using underscore.js which is supported on the cloud:
var match = _.find(results, function(object){ return object.get("place_id") == 1234; });
Just make sure your have var _ = require('underscore'); on top of your js file.

How to access data in JSON format using javascript

I'm trying to figure out on how to access data in JSON format and have gone a whole day searching for ways but I still can't find a solution to fit my needs. The closest relative question to my problem is this question but to no avail.
Basically I am retrieving data from $.ajax() which returns in JSON format.
[{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
{"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
{"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}]
[{"date":"2013-02-01","visits":63},
{"date":"2013-02-02","visits":30}]
My problem is how can I access the elements inside the JSON, say I want to get all values of "nv" or all values of "date" on the second bracket, in javascript? I Am new at things like these so am not familiar with the terminologies, sorry for that.
Below is my code:
var Data = $.ajax({
url: url,
type: 'POST',
dataType:"json",
async: false
}).responseText;
console.log(Data);
url is a variable that is passed inside my function in case you might ask.
Update: See Anthony Grist's comment on your question, I missed the fact that your JSON is invalid. Since he hasn't posted an answer, I'll pick it up.
Your JSON is invalid because you're returning two separate arrays, this one:
[{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
{"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
{"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}]
and this one:
[{"date":"2013-02-01","visits":63},
{"date":"2013-02-02","visits":30}]
You can't do that, because the top level of a JSON document must be one thing (an object or an array).
You could return an object with properties for each array:
{
"vdata":
[{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
{"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
{"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}
],
"datedata":
[{"date":"2013-02-01","visits":63},
{"date":"2013-02-02","visits":30}
]
}
After parsing (see below), you can access that data like this:
console.log(data.vdata[0].v); // "233"
console.log(data.datedata[0].date); // "2013-02-01"
Or an array with two slots, with each slot having one of your arrays in it:
[
[{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
{"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
{"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}
],
[{"date":"2013-02-01","visits":63},
{"date":"2013-02-02","visits":30}
]
]
After parsing (see below), you can access that data like this:
console.log(data[0][0].v); // "233"
console.log(data[1][0].date); // "2013-02-01"
Personally, I prefer using an object, since then it's clear which array I'm accessing.
Original answer:
jQuery will parse the JSON into an object for you and pass that to the success function, which you can then access just like any other object. In your case, the top level is an array. So:
$.ajax({
url: url,
type: 'POST',
dataType:"json",
async: false,
success: function(data) {
// Use the line from above that suits the way
// you updated your JSON structure
}
});
Side note: async: false is deprecated and will be removed at some point. It's generally not a good idea to do synchronous ajax requests, it tends to lock up the UI of the browser during the request. Instead, just structure your code to continue processing when the success callback is triggered.
If I understand your problem you need to access the same key for all objects in this array.
There is no direct method to do that, you have to iterate through all objects in this array and then find the desired key in each of those objects.
JSON.parse() will convert this string into a Javascript Object (JSON)
var myData = JSON.parse(Data);
for(var i = 0; i < myData.length; i++) {
console.log("This is the nv value of the " + i + " object: " + myData[i].nv);
}

Deserializing JavaScript object instance

I am working on an app that heavily uses JavaScript. I am attempting to include some object-oriented practices. In this attempt, I have created a basic class like such:
function Item() { this.init(); }
Item.prototype = {
init: function () {
this.data = {
id: 0,
name: "",
description: ""
}
},
save: function() {
alert("Saving...");
$.ajax({
url: getUrl(),
type: "POST",
data: JSON.stringify(this.data),
contentType: "application/json"
});
}
}
I am creating Item instances in my app and then saving them to local storage like such:
Item item = new Item();
window.localStorage.setItem("itemKey", JSON.stringify(item));
On another page, or at another time, I am retriving that item from local storage like such:
var item = window.localStorage.getItem("itemKey");
item = JSON.parse(item);
item.save();
Unfortunately, the "save" function does not seem to get reached. In the console window, there is an error that says:
*save_Click
(anonymous function)
onclick*
I have a hunch that the "(anonymous function)" is the console window's way of saying "calling item.save(), but item is an anonymous type, so I am trying to access an anonymous function". My problem is, I'm not sure how to convert "var item" into an Item class instance again. Can someone please show me?
Short answer:
Functions cannot be serialized into JSON.
Explanation:
JSON is a cross-platform serialization scheme based on a subset of JS literal syntax. This being the case, it can only store certain things. Per http://www.json.org/ :
Objects: An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).
Arrays: An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
values: A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
Functions cannot be serialized into JSON because another non-JS platform would not be able to unserialize and use it. Consider the example in reverse. Say I had a PHP object at my server which contained properties and methods. If I serialized that object with PHP's json_encode() and methods were included in the output, how would my JavaScript ever be able to parse and understand PHP code in the methods, let alone use those methods?
What you are seeing in your resulting JSON is the toString() value of the function on the platform you're using. The JSON serilizer calls toString() on anything being serialized which isn't proper for JSON.
I believe your solution is to stop storing instances in JSON/local storage. Rather, save pertinent data for an instance which you set back to a new instance when you need.
I know this question is answered already, however I stumbled upon this by accident and wanted to share a solution to this problem, if anyone is interested.
instead of doing this:
var item = window.localStorage.getItem("itemKey");
item = JSON.parse(item);
item.save();
do something like this:
// get serialized JSON
var itemData = window.localStorage.getItem("itemKey");
//instantiate new Item object
var item = new Item();
// extend item with data
$.extend(item, JSON.parse(itemData));
// this should now work
item.save();
this will work so long as the function you are wanting to call (ie, save()) is prototypal and not an instance method (often times the case, and is indeed the case in the OP's original question.
the $.extend method is a utility method of jquery, but it is trivial to roll your own.
You cant do that, how can javascript possibly knows that item have a save function ? json doesnt allow functions as datas. just read the json spec , you cant save functions.
what you need to do is to create a serialize and deserialize method in the hash you want to stock. that will specifiy what to export and how you can "wake up" an object after parsing the corresponding json string.
You can only store plain Objects in DOMstorages (cookies, urlparams..., everything that needs [de]serialisation through JSON.stringify/JSON.parse). So what you did when sending the ajax data
ajaxsend(this.data);
also applies to string serialisation. You can only store the data, not the instance attributes (like prototype, constructor etc.). So use
savestring(JSON.stringify(item.data));
which is possible because item.data is such a plain Object. And when restoring it, you will only get that plain data Object back. In your case it's easy to reconstruct a Item instance from plain data, because your Items hold their values (only) in a public available property:
var item = new Item;
item.data = JSON.parse(getjsonstring());
Disclaimer
Not a full time time J.S. Developer, answer may have some minor bugs:
Long Boring Explanation
As mentioned by #JAAulde, your object cannot be serialized into JSON, because has functions, the technique that you are using doesn't allow it.
Many people forget or ignore that the objects that are used in an application, may not be exactly the same as saved / restored from storage.
Short & quick Answer
Since you already encapsulate the data members of your object into a single field,
you may want to try something like this:
// create J.S. object from prototype
Item item = new Item();
// assign values as you app. logic requires
item.data.name = "John Doe";
item.data.description = "Cool developer, office ladies, love him";
// encoded item into a JSON style string, not stored yet
var encodedItem = JSON.stringify(item.data)
// store string as a JSON string
window.localStorage.setItem("itemKey", encodedItem);
// do several stuff
// recover item from storage as JSON encoded string
var encodedItem = window.localStorage.getItem("itemKey");
// transform into J.S. object
item.data = JSON.parse(encodedItem);
// do other stuff
Cheers.

Categories

Resources