i have a realtime database from firebase with 9386 datasets in it (but that might change in the future)
thats why i want to know whats the "key" of the last event.
thats how i'm currently trying to get it to know: (with npm module qwest)
let order = "\u0022\u0024key\u0022";
let dbUrl = "https://example.firebaseio.com/users.json?limitToLast=1&orderBy=";
let end;
qwest.get(dbUrl + order)
.then(function(xhr, response) {
console.log(response);
end = response[9386]["username"];
console.log(end);
});
first question: why do i have to escape the quotation marks and the dollarsign?
second question: how can i get the "key" of the last item i'm checking for in the json (limitToLast=1).
json response looks like this:
{"9386":
{
"fromListA":"1",
"fromListB":"0",
"id":"9939",
"lastChecked":"2019-05-09 03:18:05",
"userid":"123456789",
"username":"username"
}
}
and i want to get the "9386" in a variabel.
Since you chose to use " to limit the dbUrl string, you can't use " inside that string's value without escaping it. A simpler way to define the string is to use ' to delimit it:
let dbUrl = 'https://example.firebaseio.com/users.json?limitToLast=1&orderBy="$key"';
To get the key of the object, use something like:
Object.keys(response)[0]
var response = {"9386":
{
"fromListA":"1",
"fromListB":"0",
"id":"9939",
"lastChecked":"2019-05-09 03:18:05",
"userid":"123456789",
"username":"username"
}
}
console.log(Object.keys(response)[0]);
Related
I am using this aws-sdk in nodejs to access/update dynamodb entries.
I have a document that is very long as shown in example below.
UID = 1
sort_key = abc
variable = X
variable2 = y
variable3 = z
.....
variable(n) = n2
I want to be able to structure and update from https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#update-property
so that it can detect if there is no value for a specific variable that it won't update it.
For example, on request may only have an update for variable 2 and 4 so I don't have any details on the others.
Or am I correct in assuming I have to build javascript code that will create the UpdateExpression and ExpressionAttributeValues when I detect these specific values get entered?
If thats the pattern then it's a bit tedious however I get it. thats just how it has to be done. I was just hoping there was an elegant solution.
This is what I am thinking right now. In response to comment asking for the idea in code form.
'''
# Above this a load of if statments checking if the value is null. If not the name of the variable is added to the value listofvariables json
example of json produced after checking all the keys one by one if they are null.
var obj = { "variable 1": "test", "variable 2": "test2" };
UpdateExpression = "set"
for (const key of Object.keys(obj)) {
var addMevar =" " + key + " = :" + key + ","
var addMevalue = { key : obj[key] }
var UpdateExpression = UpdateExpression.concat(addme)
var ExpressionAttributeValues = ExpressionAttributeValues.concat(addMevalue)
}
var params = {
TableName: 'Table',
Key: { HashKey : 'hashkey' },
UpdateExpression: UpdateExpression
ExpressionAttributeValues: ExpressionAttributeValues
};
'''
What I really want is something like this.
var params = {
TableName: 'Table',
Key: { HashKey : 'hashkey' },
UpdateExpression: all the value here like usual 'set blablabla =something '
ExpressionAttributeValues: {value set to the values in the rest of my code. However some flag that says if null you don't update the value in DB as empty.}
};
Ultimately I know the building of the query works. I just hoping someone knew of a better way.
The only way is to put in logic thats builds the JSON. There is no way the conditions and so on for AWS dynamo filters to know or care if something is null and not to include it.
So I've been working on this project but I'm stuck because I can't figure out how I should go about setting the other values of this new JSON object. So basically on the front end I have this:
HTML page view. The 'cat4' ID is the new object I tried to create, and illustrates the error I'm trying to fix. The problem is that I'm having trouble setting the LIMIT value of newly created objects (or multiple values at all). Here is the code where the object is created:
function sendCat()
{
window.clearTimeout(timeoutID);
var newCat = document.getElementById("newCat").value
var lim = document.getElementById("limit").value
var data;
data = "cat=" + newCat + ", limit=" + lim;
var jData = JSON.stringify(data);
makeRec("POST", "/cats", 201, poller, data);
document.getElementById("newCat").value = "Name";
document.getElementById("limit").value = "0";
}
In particular I've been playing around with the line data = "cat=" + newCat + ", limit=" + lim; but no combination of things I try has worked so far. Is there a way I can modify this line so that when the data is sent it will work? I find it odd that the line of code works but only for setting one part of the object.
The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
MDN
I think this is what you want:
const newCat = 'Meow';
const newLimit = 5;
const data = {
cat: newCat,
limit: newLimit
}
console.log(JSON.stringify(data));
What you're referring to as a 'JSON object' is actually just a javascript object, you can make one using object literal syntax. An object literal with multiple properties looks like this:
var data = {
cat: newCat,
limit: lim
};
makeRec("POST", "/cats", 201, poller, JSON.stringify(data));
assuming the fifth parameter to makeRec is supposed to be the POST request body as stringified JSON, as your code seems to imply
The Problem is the following:
I have a JSON file that has objects with the following name: "item0": { ... }, "item1": { ... }, "item2": { ... }. But I can't access them when going through an if method.
What I've done so far:
$.getJSON('/assets/storage/items.json', function(data) {
jsonStringify = JSON.stringify(data);
jsonFile = JSON.parse(jsonStringify);
addItems();
});
var addItems = function() {
/* var declarations */
for (var i = 0; i < Object.keys(jsonFile).length; i++) {
path = 'jsonFile.item' + i;
name = path.name;
console.log(path.name);
console.log(path.type);
}
}
If I console.log path.name it returns undefined. But if I enter jsonFile.item0.name it returns the value. So how can I use the string path so that it's treated like an object, or is there an other way on how to name the json items.
As others stated 'jsonFile.item' + i is not retrieving anything from jsonFile: it is just a string.
Other issues:
It makes no sense to first stringify the data and then parse it again. That is moving back and forth to end up where you already were: data is the object you want to work with
Don't name your data jsonFile. It is an object, not JSON. JSON is text. But because of the above remark, you don't need this variable
Declare your variables with var, let or const, and avoid global variables.
Use the promise-like syntax ($.getJSON( ).then)
Iterate object properties without assuming they are called item0, item1,...
Suggested code:
$.getJSON('/assets/storage/items.json').then(function(data) {
for (const path in data) {
console.log(data[path].name, data[path].type);
}
});
What you want is to use object notation using a dynamic string value as a key instead of an object key. So, instead of using something like object.dynamicName you either have use object[dynamicName].
So in your example it would be like this.
path = 'item' + i;
jsonFile[path].name
I'm afraid you cannot expect a string to behave like an object.
What you can do is this:
path = `item${i}`
name = jsonFile[path].name
I have a response with two jsons, exactly like this -
{
"redirectUrl": "http:\/\/lumoslocal.heymath.com"
},
{
"status": "SUCCESS"
}
I need to redirect on getting the response to the redirectUrl. Something like window.location.href = response.redirectUrl. But it's not working. Possibly because of two json in my response. How do I use the 'redirectUrl' of my first json?
My understanding (from the OP's comments) is that the response is coming back as a string like this: authResp = '{"redirectUrl":"http:\/\/lumoslocal.heymath.com"}, {"status":"SUCCESS"}'
Technically this is not valid JSON as one big chunk, you'll get an error (test it out below)
JSON.parse('{"redirectUrl":"http:\/\/lumoslocal.heymath.com"}, {"status":"SUCCESS"}')
To successfully parse the data (and ultimately get the redirectUrl data), follow these steps:
split the string with a comma "," character
parse the "first JSON element"
redirect to extracted redirectUrl
Here's the code for each step:
authResp = '{"redirectUrl":"http:\/\/lumoslocal.heymath.com"}, {"status":"SUCCESS"}';
// 1. split the string with a comma character:
let authArr = authResp.split(',');
// 2. parse the first JSON element:
let redirectObj = JSON.parse(authArr[0]);
// 3. redirect to extracted redirectUrl
window.location.href = redirectObj.redirectUrl;
Or, if you want to parse the entire string into an array of JSON objects you can do this:
authResp = '{"redirectUrl":"http:\/\/lumoslocal.heymath.com"}, {"status":"SUCCESS"}';
// create array of json strings, then parse each into separate array elements
authArr = authResp.split(',').map(e => JSON.parse(e));
// Finally, follow #JackBashford's code:
window.location.href = authArr.find(e => e.redirectUrl).redirectUrl;
If your two responses are in an array, it's simple, even if they're unordered:
var myJSON = [{"redirectUrl": "http:\/\/lumoslocal.heymath.com"}, {"status": "SUCCESS"}];
window.location.href = myJSON.find(e => e.redirectURL).redirectURL;
I have objects in Parse called "Post" and within that, I have columns called "title" and "content". I am trying to ask the user for an input value and save this as "remove". If the user's input value ("remove") matches a "title" value already saved in parse.com, I want to delete the entire row in parse, so that both the "title", "content" and everything else in the row is deleted. The deleting part is not working so I am wondering if my code is actually making it go through all the data saved in parse and find the one that matches the user's input and then delete it.
What am I doing incorrectly and what can I change to make it delete the entire row?
Thank you in advance.
function getPosts(){
var query = new Parse.Query(Post);
query.find({
success: function(results){
for(var i in results){
var title = results[i].get("title");
var content = results[i].get("content");
var remove = $("#post-remove").val();
console.log("Remove: "+remove);
console.log("MAC Address: " +title);
console.log("place: "+content);
if (title == remove)
{
window.alert("The MAC address matches.");
console.log(remove+" matches " + title+ " and is located in " +content);
var Post = Parse.Object.extend("Post");
var query = new Parse.Query(Post);
query.find("objectId", {
success: function(yourObj){
//console.log(yourObj);
//Post.destroy({}); //if title matches remove, delete the Post (title and content) (but it's not deleting it)
Post.remove("title");
Post.remove("content");
}
});
}
}
}
});
}
To clarify and add a bit to #JakeT's acceptable answer:
1) find objects to delete like this:
function postsMatching(title) {
var Post = Parse.Object.extend("Post");
var query = new Parse.Query(Post);
query.equalTo("title", title);
return query.find();
}
2) Delete an array of parse objects like this:
Parse.Object.destroyAll(posts);
3) Put the two ideas together (returning a promise to find then delete) like this:
var title = $("#post-remove").val();
postsMatching(title).then(function(posts) {
console.log("deleting " + JSON.stringify(posts));
Parse.Object.destroyAll(posts);
}, function(error) {
console.log("error " + JSON.stringify(error));
});
First of, you can use the Parse.Query.equalTo(key, value) method to filter for the Post/s you are looking for. That will render a lot of your logic unnecessary.
Additionally, since most parse calls are asynchronous, I would suggest learning about Parse Promises and using those instead of the call backs you're using.
Finally, you don't need a second nested query, since you already have the object you are trying to destroy. You just need to call destroy() on that object, and if you have some extra content you need to take care of deleting (i.e., your 'content' is a pointer to another object that is owned only by the Post you are deleting), you should set up a beforeDestroy() trigger for the Post object in your cloud code that will delete that pointer as well.