formatting a json object - javascript

Im trying to use json to store some values from a page and then access these values/variables
later in a php file. Now the thing is that I'm new to json and javascript in general and Im
struggling for hours to find a solution to a problem that might be stupidly simple for you
guys who have experience in this:
Now I have this:
var invoice_data = {
"client":[
{
"client-name" : "",
"client-address" : "",
"client-address-2" : "",
"client-city-state" : "",
"client-country" : ""
}
],
"shoppingcart":[
{
"1" : {"item-name":"", "qty":"", "price":"", "discount":"", "subtotal":""}
}
],
};
So is this inheritance thing im not really getting. So just as I've created "client" object
im creating "shoppingcart", now the thing is that when user orders more than an item there should be created another sub-object that would store it's details too.So im assuming like:
"shoppingcart":[
{
"1" : { "item-name":"", "price":"", "discount":"" }
"2" : { "item-name":"", "price":"", "discount":"" }
}
],
So when I console.log(invoice_data.shoppingcart); I get the "shoppingcart" object, but I
cant access invoice_data.shoppingcart.1 or invoice_data.shoppingcart.2, is there any way I can access 1 or 2 sub-object just as access invoice_data.shoppingcart or invoice_data.client?
Thank you.
Edit: I can access it as an array, im not interested in that option. Ideally i'd like to access the sub-object via it's name.

Remove the array syntax:
Change this:
"client":[
{
"client-name" : "",
"client-address" : "",
"client-address-2" : "",
"client-city-state" : "",
"client-country" : ""
}
]
to this:
"client": {
"client-name" : "",
"client-address" : "",
"client-address-2" : "",
"client-city-state" : "",
"client-country" : ""
}
The same goes for shopping cart.

You can't access invoice_data.shoppingcart.1 because 1 is not a valid Javascript variable name. If the key for an object isn't a valid variable name, you have to use array notation: invoice_data.shoppingcart[1].
EDIT: I didn't see it, but as Matt pointed out, you must remove the array syntax as well.

Your shopping_cart is an array.
You don't want:
shopping_cart : {
1 : { name : "...", price : "..." },
2 : { ... }
}
You want:
shopping_cart : [
{ name : "..." },
{ ... }
]
Then you would access that by saying:
shopping_cart[0].name;
shopping_cart[0].price;
Et cetera.
Arrays also start at 0 and not 1.
And this isn't inheritance: it's just a collection of things.

Related

MongoDB How to filter db.adminCommand output

does anybody know how to filter mongodb db.adminCommand output? Because if I run this command db.adminCommand({ "currentOp": true, "op" : "query", "planSummary": "COLLSCAN" }) I get a huge JSON output but I'm only interested in some fields ( like secs_running, op, command, $db)
Many thanks!
You can add the filters straight to the command object like the following:
var commandObj = {
"currentOp" : 1,
"waitingForLock" : true,
"$or" : [
{
"op" : {
"$in" : [
"insert",
"update",
"remove"
]
}
},
{
"command.findandmodify" : {
"$exists" : true
}
}
]
};
db.adminCommand(commandObj);
You can see some filter examples on the MongoDB docs: https://docs.mongodb.com/manual/reference/method/db.currentOp/#examples
Just re-read your question and I think you might of meant just projecting fields back from the database that you care about? if that's the case you can just execute a map on top of the current results so you only see what you care about?
db.adminCommand(commandObj).inprog.map(x => x.opid};

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.

Access nested JSON in json2html

I'm using json2html to create a report for a given JSON file. I was wondering what exactly the syntax is to access nested objects and their fields. For example,
var jsonData = {
"field1": "value1",
"field2": "value2",
"nestedObject": {
"nestedField1": "nestedValue1",
"nestedField2": "nestedValue2"
}
}
What's the syntax to access "nestedField1"? The transform that I'm using is,
var transform = [
{tag : "h1", html : "${field1}"},
{tag : "article", html : "${field2}"},
{tag : "article", html : "${nestedObject}" }
]
The last statement html : "${nestedObject}" returns [Object object] as expected. But, I can't seem to access its fields.
"${nestedObject.nestedField1}"
This should do the trick.
Just like how you'd access it in JS:
jsonData.nestedObject.nestedField1
I should have tried everything that seemed intuitive.
The simple way is,
{ tag : "article", html : "the first nested field is ${nestedObject.nestedField1}" }

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