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.
Related
I tried several approches and none of them works. I think this is because I am using JSON returned by django DRF.
I want to create a list of IFSC using this JSON in Jquery in my HTML template itself.
This is how my api returns JSON for any queryset.
{
"count": 134,
"next": "http://127.0.0.1:8000/api/bankdetailapi/?limit=5&offset=5&q=ABHY",
"previous": null,
"results": [
{
"ifsc": "ABHY0065001",
"bank": {
"name": "ABHYUDAYA COOPERATIVE BANK LIMITED",
"id": 60
},
"branch": "RTGS-HO",
"address": "ABHYUDAYA BANK BLDG., B.NO.71, NEHRU NAGAR, KURLA (E), MUMBAI-400024",
"city": "MUMBAI",
"district": "GREATER MUMBAI",
"state": "MAHARASHTRA"
},
{
"ifsc": "ABHY0065002",
"bank": {
"name": "ABHYUDAYA COOPERATIVE BANK LIMITED",
"id": 60
},
"branch": "ABHYUDAYA NAGAR",
"address": "ABHYUDAYA EDUCATION SOCIETY, OPP. BLDG. NO. 18, ABHYUDAYA NAGAR, KALACHOWKY, MUMBAI - 400033",
"city": "MUMBAI",
"district": "GREATER MUMBAI",
"state": "MAHARASHTRA"
},
{
"ifsc": "ABHY0065003",
"bank": {
"name": "ABHYUDAYA COOPERATIVE BANK LIMITED",
"id": 60
},
"branch": "BAIL BAZAR",
"address": "KMSPM'S SCHOOL, WADIA ESTATE, BAIL BAZAR-KURLA(W), MUMBAI-400070",
"city": "MUMBAI",
"district": "GREATER MUMBAI",
"state": "MAHARASHTRA"
}
]
}
The code I tried:
$(document).ready(function(){
var value = $('#q').val()
$.getJSON("http://127.0.0.1:8000/api/bankdetailapi/?q="+ value, function(data){
var text = `IFSC: ${data.ifsc}`
})
)}
It throws error in browser console that Uncaught ReferenceError: text is not defined . I want to use this IFSC list as autocomplete suggestions.
$("#q").keyup(function(){
var value = $('#q').val()
$.getJSON("http://127.0.0.1:8000/api/bankdetailapi/?q="+ value, function(data){
var text = ['']
for (var i=0;i<data.results.length;++i){text.push(data.results[i].ifsc)}
// var text = `IFSC: ${data.results.ifsc}`
console.log(text)
By using push method and iterating on whole data i managed to get list of all IFSC values.
I have a database of musical works and in these works the are information about the owners of that works. The owner can be an editor or a composer. There can be many composers and many editors.
Editors and composers have a publishing relationship that is indicated by their attribute called link. So, if an editor has a link = 5 and the composer too, they are linked. Or the editor is the publisher of that composer.
I use this query to get only the musical works that are from the editor I want.
db.works.find({'pro_owners.codigo_ecad': 5546730})
.projection({})
.sort({_id:-1})
.limit(100)
And it retrieves me some documents like these:
{
"_id": "6042617f0732f22da210e7a6",
"codigo_ecad": 16403107,
"iswc": "T0401990268",
"titulo": "YA INTENTE COMPREENDER",
"situacao": "LB",
"data_inclusao": "2017-06-02T03:00:01.000Z",
"pro_owners": [
{
"codigo_ecad": 8096286,
"owner": "JOSIEL DEL CID",
"category": "CA",
"percent": 0,
"link": "2",
"_id": "60426160dca0dd0dc8290d41"
},
{
"codigo_ecad": 381928,
"owner": "THALES ROBERTO DA SILVA",
"category": "CA",
"percent": 0.75,
"link": "1",
"_id": "6042615bdca0dd0dc8290d32"
},
{
"codigo_ecad": 5546730,
"owner": "THALES ROBERTO DA SILVA - EIRELI - ME",
"category": "E",
"percent": 0.25,
"link": "1",
"_id": "6042615bdca0dd0dc8290d33"
}
],
"client_name": "Datha Editora"
}
I would like to know if there is a way query and receive only the unique linked owners of the editor I am interested in. In the above case, just:
{
"codigo_ecad": 381928,
"owner": "THALES ROBERTO DA SILVA",
"category": "CA",
"percent": 0.75,
"link": "1",
"_id": "6042615bdca0dd0dc8290d32"
}
The next step would be a $lookup to the owners collection to return these results with their full data. But it is a plus.
You can accomplish that with aggreation:
$match to select only document containing a pro_owner with the matching code
$addFields with $filter to extract the matching pro_owner into a new field
$addFields/$project with $filter to limit the pro_owners list to those with the same link value as the new field
I have an array of one element containing several objects. I don't know how to work with these objects. I'd like each object to be turned into an element of an array, so that I'll be able to refer to Array[0].Time to get "36:50" or Array[2].Seconds to get 2235.
Link to Json: https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/cyclist-data.json
Although it's very easy to deal with objects I converted it for you in arrays. Use Array#map to iterate through your array over the objects and map every old entry to a new one.
Create for each element a new empty array and add to this for every entry a new entry. Use for this Object.values to get the values.
Note: The sequence from the entries in the array I can't change without extra programming and it's mandatory that the objects allways have this structure (otherwise the output would change).
let arr = [
{
"Time": "36:50",
"Place": 1,
"Seconds": 2210,
"Name": "Marco Pantani",
"Year": 1995,
"Nationality": "ITA",
"Doping": "Alleged drug use during 1995 due to high hematocrit levels",
"URL": "https://en.wikipedia.org/wiki/Marco_Pantani#Alleged_drug_use"
},
{
"Time": "36:55",
"Place": 2,
"Seconds": 2215,
"Name": "Marco Pantani",
"Year": 1997,
"Nationality": "ITA",
"Doping": "Alleged drug use during 1997 due to high hermatocrit levels",
"URL": "https://en.wikipedia.org/wiki/Marco_Pantani#Alleged_drug_use"
},
{
"Time": "37:15",
"Place": 3,
"Seconds": 2235,
"Name": "Marco Pantani",
"Year": 1994,
"Nationality": "ITA",
"Doping": "Alleged drug use during 1994 due to high hermatocrit levels",
"URL": "https://en.wikipedia.org/wiki/Marco_Pantani#Alleged_drug_use"
},
{
"Time": "37:36",
"Place": 4,
"Seconds": 2256,
"Name": "Lance Armstrong",
"Year": 2004,
"Nationality": "USA",
"Doping": "2004 Tour de France title stripped by UCI in 2012",
"URL": "https://en.wikipedia.org/wiki/History_of_Lance_Armstrong_doping_allegations"
}];
let res = arr.map(obj => {
let arr = [];
Object.values(obj).forEach(val => arr.push(val));
return arr;
});
console.log(res);
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.
I have this JSON & what I want to do is to make genres like this action|adventure|comedy
{
"id": 1,
"key": "deadpool",
"name": "Deadpool",
"description": "A former Special Forces operative turned mercenary is subjected to a rogue experiment that leaves him with accelerated healing powers, adopting the alter ego Deadpool.",
"genres": [
"action",
"adventure",
"comedy"
],
"rate": 8.6,
"length": "1hr 48mins",
"img": "assets/images/movie-covers/deadpool.jpg"
},
{
"id": 2,
"key": "we-are-the-millers",
"name": "We're the Millers",
"description": "A veteran pot dealer creates a fake family as part of his plan to move a huge shipment of weed into the U.S. from Mexico.",
"genres": [
"adventure",
"comedy",
"crime"
],
"rate": 7,
"length": "1hr 50mins",
"img": "assets/images/movie-covers/we-are-the-millers.jpg"
}
my component code snippet
data => {
this.movies = data;
var tempArr= data
var genres;
let genresWithPipe=[];
let len= tempArr.length;
for(var i=0; i<len; i++){
genres=tempArr[i].genres+'|';
// console.log(tempArr[i].genres)
for(var j=0;j<genres.length; j++){
if(j<genres.length-1)
genres[j]= genres[j]+'|';
console.log(genres,data);
//genresWithPipe=genres;
}
}
console.log(this.movies,genres)
}
I have tried to do it with the help of for loop in my component but then when I am displaying it in the html with the help of *ngFor then because it's a local variable,it won't show up. If I store array values in a global variable then the variable only store the last array.
You can use map method in order to achieve your requirement and obtain a more cleaner solution.
The map() method creates a new array with the results of calling a
provided function on every element in the calling array.
Also, you can use join method in order to obtain the structure action|adventure|comedy with | delimiter.
let array=[{ "id": 1, "key": "deadpool", "name": "Deadpool", "description": "A former Special Forces operative turned mercenary is subjected to a rogue experiment that leaves him with accelerated healing powers, adopting the alter ego Deadpool.", "genres": [ "action", "adventure", "comedy" ], "rate": 8.6, "length": "1hr 48mins", "img": "assets/images/movie-covers/deadpool.jpg" }, { "id": 2, "key": "we-are-the-millers", "name": "We're the Millers", "description": "A veteran pot dealer creates a fake family as part of his plan to move a huge shipment of weed into the U.S. from Mexico.", "genres": [ "adventure", "comedy", "crime" ], "rate": 7, "length": "1hr 50mins", "img": "assets/images/movie-covers/we-are-the-millers.jpg" }];
array=array.map(function(item){
item.genres=item.genres.join('|');
return item;
});
console.log(array);
A good solution with Array.map() has been proposed, here is another option with Array.forEach():
const data = [{
"id": 1,
"key": "deadpool",
"name": "Deadpool",
"description": "A former Special Forces operative turned mercenary is subjected to a rogue experiment that leaves him with accelerated healing powers, adopting the alter ego Deadpool.",
"genres": [
"action",
"adventure",
"comedy"
],
"rate": 8.6,
"length": "1hr 48mins",
"img": "assets/images/movie-covers/deadpool.jpg"
},
{
"id": 2,
"key": "we-are-the-millers",
"name": "We're the Millers",
"description": "A veteran pot dealer creates a fake family as part of his plan to move a huge shipment of weed into the U.S. from Mexico.",
"genres": [
"adventure",
"comedy",
"crime"
],
"rate": 7,
"length": "1hr 50mins",
"img": "assets/images/movie-covers/we-are-the-millers.jpg"
}
]
const genres = [];
data.forEach(film => genres.push(film.genres.join("|")));
console.dir(genres);
Note that your data definitely doesn't look like what you put in the code sample, it must be wrapped with [].