I have a code snippet of JavaScript:
mf.profile.push({
"Site": {
"Name": "Jack Montana",
"Identity": 61026032,
"Email": "jack#gmail.com",
"Phone": "+14155551234",
"Gender": "M",
}
});
mf.event.push("Product viewed", {
"Product name": "Casio Chronograph Watch",
"Category": "Mens Accessories",
"Price": 59.99,
"Date": new Date()
});
Now my question is what does mf.profile.push or mf.event.push signify?
Is mf an object and profile a function? or both are classes and push is a function?
what does mf.profile.push or mf.event.push signify
The mf variable is an Object literal and the profile/event are properties (may of type array) belongs to this object.
The push() is a method that will add the items passed as parameters to those attributes.
Related
Building a react native app using CosmosDB and it's SQL api.
Per their documentation, I can add an object to a container like this:
const CosmosClient = require('#azure/cosmos').CosmosClient;
const client = new CosmosClient({ endpoint, key });
const myNewObject = {foo: "bar"}
await client
.database(databaseId)
.container(containerId)
.items.create(myNewObject);
And I can confirm this works.
What I'm trying to do tho, is place data into that {foo: "bar"} document that already exists.
So far I've tried chaining the .item method, but it does't work.
await client
.database(databaseId)
.container(containerId)
.item(idOfMyNewObject) // The existing object I want to create a child in
.item('myNewChildObject') // new child of the parent
.create(newEntry); // new entry in the new child
Any ideas? the documentation doesn't seem to talk about this.
There's no method on the container that does this for you. You must define the structure of the data yourself in your code. Here is an example of a customer record which has both an array of addresses as well as an embedded object.
const customer = {
"id": "000242A2-BF40-4220-864B-2770CAA38F5D",
"type": "customer",
"customerId": "000242A2-BF40-4220-864B-2770CAA38F5D",
"title": "",
"firstName": "Timothy",
"lastName": "Kelly",
"emailAddress": "timothy4#adventure-works.com",
"phoneNumber": "193-555-0189",
"creationDate": "2014-03-14T00:00:00",
"addresses": [
{
"addressLine1": "9918 Scottsdale Rd.",
"addressLine2": "",
"city": "Novato",
"state": "CA ",
"country": "US",
"zipCode": "94947",
"location": {
"type": "Point",
"coordinates": [
-122.764,
38.0852
]
}
}
],
"password": {
"hash": "LvEbgjonEPU11HEeSXqdzTsmqNeUfuhxBNL82vGlCWA=",
"salt": "61626BAE"
},
"salesOrderCount": 1
}
kI have a problem with the library https://github.com/JSONPath-Plus/JSONPath at the latest version.
Example:
{
"firstName": "John",
"lastName": "doe",
"age": 26,
"address": {
"streetAddress": "naist street",
"city": "Nara",
"postalCode": "630-0192"
},
"phoneNumbers [1]": [
{
"type": "iPhone",
"number": "0123-4567-8888"
},
{
"type": "home",
"number": "0123-4567-8910"
}
]
}
Now i want to get "phoneNumbers [1]" with
path: $..['phoneNumbers [1]']
Here is a Demo Page for testing: https://jsonpath-plus.github.io/JSONPath/demo/
That did not work because of the square brackets inside of the String.
Do anyone know how to solve this Problem.
I have a lot of Json Objects containing strings with square brackets, so if there is a solution not only for a specific case.
Is there any option to escape characters so that the problem will be solved?
The json Object above is only a Example Code to describe the Problem.
The Problem also occurs when only using JSONPath so it is not limited to that Library.
https://jsonpath.com/
This appears to be a bug in JSONPath-Plus. The jsonpath library can handle it.
const data = JSON.parse(`{
"firstName": "John",
"lastName": "doe",
"age": 26,
"address": {
"streetAddress": "naist street",
"city": "Nara",
"postalCode": "630-0192"
},
"phoneNumbers [1]": [
{
"type": "iPhone",
"number": "0123-4567-8888"
},
{
"type": "home",
"number": "0123-4567-8910"
}
]
}`);
const result = jsonpath.query(data, "$..['phoneNumbers [1]']");
console.log(result);
<script src="https://unpkg.com/jsonpath#1.1.1/jsonpath.js"></script>
There's not much you can do about this beyond:
Changing your data structure
Changing your library
Filing a bug report
There is a workaround you can use only with jsonpath-plus
$[?(#property == "phoneNumbers [1]")]
I'm working to have a CRUD with a JSON file, but I have no idea how to manipulate many levels of JSON. So I have the following JSON code. What should I do, for example, if I want to add a new assistant? Is this even possible?
{
"events": [{
"id": "1",
"name": "Noches de trova",
"address": "Degollado #93 Centro, 28000 Colima City",
"city": "Colima",
"date": "Oct 10",
"datetime": "07:00 PM",
"price": "0",
"description": "Noches para escuchar, sentir y pasarla bien.",
"image": "img/banner1.jpg",
"publisher": "Noches café",
"assistants": [{
"name": "Alfredo Tomas Perez Prado",
"address": "Las brisas #356 Col. Colinas del rey",
"age": "29"
}],
"activities": [{
"name": "Registro",
"place": "Explanada del edificio 1",
"time": "07:00-07:30 PM"
}]
}]
}
In this example just load the json into a variable and you are good to go:
var data = {
"events": [{
"id": "1",
"name": "Noches de trova",
"address": "Degollado #93 Centro, 28000 Colima City",
"city": "Colima",
"date": "Oct 10",
"datetime": "07:00 PM",
"price": "0",
"description": "Noches para escuchar, sentir y pasarla bien.",
"image": "img/banner1.jpg",
"publisher": "Noches café",
"assistants": [{
"name": "Alfredo Tomas Perez Prado",
"address": "Las brisas #356 Col. Colinas del rey",
"age": "29"
}],
"activities": [{
"name": "Registro",
"place": "Explanada del edificio 1",
"time": "07:00-07:30 PM"
}]
}]
}
data.events[0].assistants.push({name: 'John', address: '1st Street', age: 55})
console.log(data.events[0].assistants)
If you need to find the event by some property you would then use filter/find to get to it and to add the event. But otherwise is just JS object/array access.
So you can load the json, manipulate it and then export it.
Since JSON as the acronym meaning said is a valid Javascript object. You can do all valid JS operation with it.
For Read, evaluated the text to a javascript via JSON.parse method.
For Creating an array element. Use JS operation for push(), concat()
or even inline array addition.
For Update, you could update the value of array directly as Javascript
allows.
For Delete, you can use operation such as splice() or pop(), shift().
depending on what you need.
The keyword here is the JSON is a Javascript notation object. So what ever you can use in Javascript object/array can be used in JSON CRUD.
I have following JSON data but I don't know how to iterate through it and read its all values:
var students = {
"student1": {
"first_name": "John",
"last_name": "Smith",
"age": 24,
"subject": [{
"name": "IT",
"marks": 85
},
{
"name": "Maths",
"marks": 75
},
{
"name": "English",
"marks": 60
}
]
},
"student2": {
"first_name": "David",
"last_name": "Silva",
"age": 22,
"subject": [{
"name": "IT",
"marks": 85
},
{
"name": "Maths",
"marks": 75
},
{
"name": "English",
"marks": 60
}
]
}
};
I would like to use following methods to do the needful:
Using for in loop
Using simple for loop
Using $.each in jQuery
I will prefer to display above values in <ul> <li> nicely formatted.
Also, please suggest me what will be look of above JSON data if I put it in an external .json file?
You can use for in loop to iterate over the object, as it iterates over the properties of an object in an arbitrary order, and needs to use .hasOwnProperty, unless inherited properties want to be shown.
Now about accessing the object, let's say I have a JSON like
var myJson={name:"john",age:22,email:"email#domain.com"};
and I need to access the value of name i would simply use . operator using the myJson variable i.e console.log(myJson.name) will output john. because it will be treated as an object, now if I make a little change and make the object like below
var myJson=[{name:"john",age:22,email:"email#domain.com"}];
now if you try to access the value of the property name with the same statement above you will get undefined because the [] will now treat it as an object(JSON) with an array of 1 person or a JSON Array, now if you access it like console.log(myJson[0].name) it will print john in console what if there was more than one person in the array? then it will look like following
var myJson=[
{name:"john",age:22,email:"john#domain.com"},
{name:"nash",age:25,email:"nash#domain.com"}
];
console.log(myJson[0].name) will print john and console.log(myJson[1].name) will print nash so as I mentioned in the start that you should use for in loop for iterating over an object and if we want to print all the names of the person in the JSON Array it will be like.
for(var person in myJson){
console.log(myJson[person].name, myJson[person].age, myJson[person].email);
}
it will output in the console like below
john, 22, john#domain.com
nash, 25, nash#domain.com
I have tried to keep it simple so that you understand you can look into for in and hasOwnProperty, in your case you have a nested object in which property/key subject is an array so if I want to access the first_name of student1 i will write students.student1.first_name and if I want to print the name of the first subject of student1 I will write students.student1.subject[0].name
Below is a sample script to print all the students along with their subjects and marks and personal information since you JSON is nested I am using a nested for in, although Nested iterations are not necessarily a bad thing, even many well-known algorithms rely on them. But you have to be extremely cautious what you execute in the in the nested loops.
For the sake of understanding and keeping the given example of json object, i am using the same to make a snippet. Hope it helps you out
var students = {
"student1": {
"first_name": "John",
"last_name": "Smith",
"age": 24,
"subject": [{
"name": "IT",
"marks": 85
},
{
"name": "Maths",
"marks": 75
},
{
"name": "English",
"marks": 60
}
]
},
"student2": {
"first_name": "David",
"last_name": "Silva",
"age": 22,
"subject": [{
"name": "IT",
"marks": 85
},
{
"name": "Maths",
"marks": 75
},
{
"name": "English",
"marks": 60
}
]
}
};
$("#print").on('click', function() {
for (var student in students) {
console.log(students[student].first_name + '-' + students[student].last_name);
for (var subject in students[student].subject) {
console.log(students[student].subject[subject].name, students[student].subject[subject].marks);
}
}
setTimeout('console.clear()', 5000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="print" value="print-now">
department {
"_id": "1",
"department": "Computers",
"type": "Department",
"room_no": "102",
"HOD": "Mr. G Rahul",
"floor": "1st Floor"
}
student {
"_id": "fdf370e2f43d4af1b505b8913502a5e4",
"_rev": "1-16df9a4cd45ca69009ab6c9767425a8e",
"student Name": "H Ravi",
"date_of_birth": "March 1, 1993",
"roll_no": "55",
"inter_marks": "820",
"secondary_marks": "420"
"department_id": "1",
"type": "student"
}
Map Function
function(doc) {
var id,department,student,hod,dob;
if(doc.type == 'student') {
id = doc.department_id;
dob = new Date(doc.date_of_birth)
student = doc;
}
}
emit(dob, {'_id': id,"student_doc": student});
}
After writing map function we call view by using URL "//localhost:5984/db_name/_design/design_name/_view/view_name". In that URL we will append ?include_docs=true after "view_name"("//localhost:5984/db_name/_design/design_name/_view/view_name/?include_docs=true") to get the docs of by using _id in emit, example: emit(dob,{"_id": id}) it will return the docs of linked id...My question is how can we access that docs in reduce function.
You can’t, the docs are fetched on query time, not on indexing time, so the reduce function never gets to see that data. Sorry!