Can a Parse object be fetched with object.fetch and at the same time include its object references as in query.include?
Here is the query example:
let query = new Parse.Query("MyCollection");
query.include("MyObjectReference");
return query.find();
How to do it with a fetch command?
Parse JS SDK >= 2.0.2
It is possible to fetch one or multiple objects with include:
fetchWithInclude https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Object.html#fetchWithInclude
fetchAllWithInclude https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Object.html#.fetchAllWithInclude)
Parse JS SDK < 2.0.2
It's not possible as the docs say:
By default, when fetching an object, related Parse.Objects are not
fetched. These objects’ values cannot be retrieved until they have
been fetched like so:
var post = fetchedComment.get("parent");
post.fetch({
success: function(post) {
var title = post.get("title");
}
});
Stumbled onto this via a google search and wanted to correct the record. The accepted answer to this is not correct.
You very much CAN do what the OP is asking by using fetchWithInclude([key1,key2.subkey,key2.subkey2,etc]);
See: https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Object.html
A fetch command in Parse is essentially a find with only a "where equal to" on a single object id. So you can simply make a query for a single object id and Parse will handle it like a fetch, e.g. you can restrict a table to only allow fetch and this single object id query will still pass. I haven't read into the code, but I believe that a fetch is essentially a single object id (find) query. You can then also use the include of your find query.
Related
Let's jump straight to an example code:
create table test_json_table
(
data json not null
);
I can insert to the table like this:
const columns = { data: "{ some_json: 123 }" }; // notice that the data column is passed as string
await knex('test_json_table').insert(columns);
And get data from the table like this:
await knex('test_json_table').select();
// returns:
// [
// { data: { some_json: 123 } } // notice that the data is returned as parsed JavaScript object (not a string)
// ]
When inserting a row the JSON column needs to be passed as a serialised string. When retrieving the row, an already parsed object is returned.
This is creating quite a mess in the project. We are using TypeScript and would like to have the same type for inserts as for selects, but this makes it impossible. It'd be fine to either always have string or always object.
I found this topic being discussed at other places, so it looks like I am not alone in this (link, link). It seems like there is no way to convert the object to string automatically. Or I am missing something?
It'd be nice if knex provided a hook where we could manually serialise the object into string when inserting.
What would be the easiest way to achieve that? Is there any lightweight ORM with support for that? Or any other option?
You could try objection.js that allows you to declare certain columns to be marked as json attributes and those should be stringified automatically when inserting / updating their values https://vincit.github.io/objection.js/api/model/static-properties.html#static-jsonattributes
I haven't tried if it works with mysql though. I don't see any reason why it wouldn't.
I think the easiest way using jsonb data type. mysql json type
We prefer postgresql for this kind of problem at office, easier and solid database for your problem.
Well you could call your own function before inserting that converts all objects to string and call it every time before you insert.
You can probably wrap knex to do it automatically as well.
I am trying to make a chat app with firebase real time database. I store chats between 2 users as an JSON array in firebase.
Initially I when user used to send message, I used to set whole chat array. But I soon realised that's not a good idea as array will grow.
await firebase.database().ref("chats/" + chatId).set(messages)
When I checked official documentation on how to handle Arrays in firebase, I realised I can use push() instead. I am doing something like this now:
let messageRef = firebase.database().ref("chats/" + chatId)
await messageRef.push().set(message);
It causes 2 problems, one is it generates unique keys and other is when I fetch the chat it returns JSON object instead of Array.
I want something like this:
Instead after using push I am getting:
What's the best way to achieve what I want?
As you can see calling push() will generate a key for you.
Two solutions:
• You let Firebase generate unique key for you and transform the JSON object into an array on client side:
firebase.database().ref("chats/" + chatId).once("value").then(data => {
console.log(Object.values(data.val()));
});
Read more here https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Object/values
• You use your own keys ("0", "1", "2"...)
firebase.database().ref("chats/" + chatId).child(key).set(msg);
The inconvenience here is you need to know the key. You can use messages.length or store a new field with the size of messages (use transaction to increment it). Don't forget to write rules to prevent users overwriting.
If you can you should use the first solution.
I have an array of JSON plots which I store in MySQL. When I retrieve this information from MySQL it is given as one long string. How can I restore this back into an array of JSON objects using Javascript? I'm running this using NodeJS and MySQL package.
My data is returned like the following:
'[{"x":0,"y":0},{"x":1,y:1},{"x":2,"y":2}]'
What I would like to be able to do is use the data like:
var data = [{"x":0,"y":0},{"x":1,"y":1},{"x":2,"y":2}];
console.log(data[0].x);
I've had a try using JSON.parse and originally stored the data using JSON.stringify on the array, but it is not behaving as I would expect.
Are there any methods or packages available to handle this?
Edit: I realize now that this is not JSON but rather objects. Apologies for the wrong terminology here, but my problem still remains.
var data = new Function ('return ' + dataString)();
The url to the spreadsheet I am querying is
docs.google.com/spreadsheets/d/1EIBhBQY1zbdBEKXsJIY1uyvdQw0b1cIBSrBE_tZvA6Y/edit?usp=sharing
The query url being used is
https://spreadsheets.google.com/tq?tqx=out:&key=1EIBhBQY1zbdBEKXsJIY1uyvdQw0b1cIBSrBE_tZvA6Y&gid=0&headers=1&tq=select%20B%2CC%2CD%20where%20(A%20matches%20%22DIS%22)
Is there a way to convert or store this result in a JavaScript array?
var dis = ["The Walt Disney Company","Entertainment",.1]
I need to be able to manipulate the data at one point and add the new data to the visualization.
Data from one of multiple queries --> Convert to array --> Manipulate data ex: multiplying an input --> data.addRows(manipulated input);
Your query does return a string containing JSON wrapped in a function call:
var responseText = 'google.visualization.Query.setResponse({…});';
This is because you specified out: as an argument for tqx (see Google Developers guides).
If you want it all raw, you can extract and parse the JSON of multiple queries and push the data to an array, so you end up with an array of arrays of row data. For your single query, you could start from something like this:
responseJSON = JSON.parse(
responseText.replace(/(^google\.visualization\.Query\.setResponse\(|\);$)/g,'')
);
var rowsArray = [];
responseJSON.table.rows.forEach(function(row){
var rowArray = [];
row.c.forEach(function(prop){ rowArray.push(prop.v); });
rowsArray.push(rowArray);
});
console.log(rowsArray); // === [["The Walt Disney Company", "Entertainment", 0.1]]
There is a more straightforward solution to this. What you get in the response is a JSONP string whose data is hold within a callback function, just as #dakab has mentioned.
Besides this, recently Google has included some extra text in the response to help with some anti-content-sniffing protections to their API. You can read more about this in this Github thread. The response you get now is an unparseable string in this form:
/*O_o*/
google.visualization.Query.setResponse({…});
One way to deal with both issues (the "comment" string and the data hidden inside the callback function) is to evaluate the function. Whether this is risky or not is something intrinsic to the JSONP format, so you must be aware of where your response comes from and decide if it's worth the risk. But, considering it comes from a request to a Google server, and in terms of parsing, it works.
So in your case, what you could do is just declare the callback function (note that you can pass your own function name in the query string, as also mentioned in the Google Developers guides) and then evaluate it. I take inspiration on this thread:
//Declare your call back function
function callback(data){
return data;
}
//Evaluate and store the data in your callback function
var result = eval(UrlFetchApp.fetch(url + uri, options).getContentText());
In "result" you'll have an already parsed JSON that you can convert to whatever you wish.
According to Google's documentation on their Visualization API for response formats, you can add a header in your request that will return JSON without the function or comment.
If you add a header named X-DataSource-Auth in your request, the Visualization API will respond in JSON format rather than JSONP format, which is the default format of the response and includes the JSON wrapped in a function handler.
However, even with this header present, the API prepends a strange string to the response: )]}' which I think has to do with the anti-content-sniffing mentioned by #Diego. Okay, Google — even with an OAuth token do you really need to do that?
So, to get at the actual JSON in that response, you can use the following Javascript to get around it. Assume responseBody is what the API actually returns to you, and that data is storing the JSON you want.
var data = JSON.parse(responseBody.replace(/^\)]\}'\n/, ''));
Assuming str is the returned JSONP formatted response:
var str = `/*O_o*/
google.visualization.Query.setResponse({"version":"0.6","reqId":"0","status":"ok","sig":"403123069","table":{"cols":[{"id":"A","label":"Timestamp","type":"datetime","pattern":"dd/MM/yyyy HH:mm:ss"},{"id":"B","label":"AskGod Search Query","type":"string"}],"rows":[{"c":[{"v":"Date(2020,9,25,12,30,5)","f":"25/10/2020 12:30:05"},{"v":"لا أعرف لماذا"}]}],"parsedNumHeaders":1}});`
console.log(JSON.parse(str.match(/(?<=.*\().*(?=\);)/s)[0]))
I need to transfer a multi-dimensional JavaScript array to another page, without using any library. What I can use is JavaScript, PHP and other languages that doesn't need a library.
I have a three-dimensional array which is build like this:
storage[category][field][multiple answers] and has a lot of values.
I need to transfer it to another page so I can get all the values like:
alert(storage[5][4][8]);
=======================================================================
Well, I can pass a normal variable to another page but I cant get the values from my array when I'm testing: storage[1][1][1] for example.The big question is how I can pass a multidimensional array to another page and still be able to get the values like this: storage[1][1][1]
As I get it I'm forced to pass all the 121 arrays you can se below to be able to access all dimensions in the array.
My array is built up like this:
storage = new Array();
for (var i1=1;i1<12;i1++){
storage[i1] = new Array();
for (var i2=1;i2<12;i2++){
storage[i1][i2] = new Array();
}
}
Without using a library like jQuery, you can convert your array to JSON, pass it via a URL and decode it on the target page. Converting it to JSON would look like:
var json_string = JSON.stringify(your_array);
Then pass it in a URL:
var your_url = "http://www.your_website.com/page.html?json_string=" + json_string;
And you could decode it back to an array like so:
var your_new_array = JSON.parse(getUrlVars()["json_string"]);
For some more reading, check out this JSON page: http://www.json.org/js.html
JSON.stringify() is supported by all major browsers. Send it to the server via a POST, then have your php retrieve the variable from $_POST and send it back.
As far as I can see there are two main ways to do what you want:
Pass the array to the webserver, and have it send it back on next request.
Store the data locally in the browser.
The first way could get pretty complicated. You would have to store the data in a database, file or cookie/session.
The second way would be the easiest. Use javascript to store the array in the browser. You can either use a cookie, or use the localStorage object.
Using a cookie would require you to serialize the data manually. It would also get passed to the server, so if you want to save bandwidth, you would want to avoid this.
The localStorage method would only store the data locally, and you also don't need to serialize anything, the browser takes care of this for you.
See the links below for more examples.
http://www.w3schools.com/html/html5_webstorage.asp
http://www.w3schools.com/js/js_cookies.asp