Delete an external .json object and save it again - javascript

I have a list of resources like the following html content loaded from the resources_data.json data I loaded to my app externally from the same server.
<div class="callout">
<div class="large-8 medium-8 small-8 columns left">Demo</div>
<div class="large-2 medium-2 small-2 columns right">
<a href="#" class="deleteResource" data-id="1" data-name="Demo">
<i class="fa fa-close red"></i> DELETE</a>
</div>
</div>
I would like to be able to delete items from this list by the "id" not having to match the "resourceName" so for every delete I will be deleting the entire object essentially I would not like to save the file back to the server to save time on the response but I am not sure if I can just delete a string of an external file without re-saving it.
MY JSON:
"calendarResources": [
{
"id": 1,
"resourceName": "Demo"
},
{
"id": "4",
"resourceName": "New Test Resource"
},
{
"id": "2",
"resourceName": "test"
},
{
"id": "5",
"resourceName": "another test"
},
{
"id": "6",
"resourceName": "new test data"
},
{
"id": "7",
"resourceName": "better one"
},
{
"id": "8",
"resourceName": "the one!"
},
{
"id": "12",
"resourceName": "Dune one"
},
{
"id": "13",
"resourceName": "res test"
}
]
I am trying to use the delete function to delete the string and upload the data back to the json again but something is going wrong here that nothing works and I get the same data again.
MY JS:
function deletingResource() {
$("body").on("click", ".deleteResource", function (e) {
e.preventDefault();
var resourceId = $(this).data("id");
var resourceName = $(this).data("name");
$.getJSON(appDirLocation + "_data/resources_data.json", function (jsonData) {
console.log(jsonData);
var resourceDeletion = ({
"id": resourceId,
"resourceName": resourceName
});
delete jsonData.calendarResources[resourceDeletion]; // delete data string
var newJsonOutput = JSON.stringify(jsonData); //stringify new data to save
var jsonFile = new BCAPI.Models.FileSystem.File(appDirLocation + "_data/resources_data.json");
jsonFile.upload(newJsonOutput).done(function () {
$("#resourcesList").html("");
console.log("RESOURCE DATA DELETED");
renderResources();
}).error(function (jqXHR) {
console.log("RESOURCES JSON FAILED DELETE: " + jqXHR.responseText);
}); // END OF JSON CREATING
console.log(newJsonOutput);
}).done(function () {
$(this).closest(".resourcesData").hide();
}).fail(function (jqXHR) {
console.log("Request failed." + "Error code: " + jqXHR.status + "Error text: " + jqXHR.statusText + "Response text: " + jqXHR.responseText);
});
});
} // DELETING RESOURCES
deletingResource();
Thanks for the help in advance...

Based on an answered question posted here also referencing the Array.prototype.filter() function I was able to resolve this with grace!
I Recommended for anybody looking to work with json files using javascript to check the Array property of the javascript library in MDN WEB DOCS
Code fixed:
jsonData.calendarResources = jsonData.calendarResources.filter(item => item.id != resourceId); // WORKING ######
var newJsonOutput = JSON.stringify(jsonData);
var jsonFile = new BCAPI.Models.FileSystem.File(appDirLocation + "_data/resources_data.json");

Related

Only show JSon by key value

I got stuck to rendered JSON data by an id, already browse over the several articles but not working.
I had ajax call:
$.ajax({
url: '../../../get/api/city.json',
dataType: 'json',
})
.done(function(data){
console.log(data);
var HTML = '';
$.each(data.city, function(i,city){
HTML += '<span>'+city.city_name+'</span>'; });
$('#title').append(HTML);
})
.fail(function(){
alert('failed');
});
And the json output is:
{"city":[
{"id":"4","year":"2014","city_name":"City A"},
{"id":"5","year":"2014","city_name":"City B"},
{"id":"6","year":"2014","city_name":"City C"}]}
My situation I created a html page to render the information for City A, what I want is to filter the above JSON data only rendered the information from city A.
Big thanks for any help from you guys.
Thanks
Try the following using Array's filter():
var info = {"city":[
{"id":"4","year":"2014","city_name":"City A"},
{"id":"5","year":"2014","city_name":"City B"},
{"id":"6","year":"2014","city_name":"City C"}]};
var res = info.city.filter(function(item){
return item.city_name =='City A';
});
console.log(res);
var HTML = '<span>'+res[0].city_name+'</span>';
$('#title').append(HTML)
HTML = '<span>'+res[0].id+'</span>';
$('#id').append(HTML);;
HTML = '<span>'+res[0].year+'</span>';
$('#year').append(HTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="title">Title: </div>
<div id="id">Id: </div>
<div id="year">Year: </div>
UPDATE:
Once your request server send data, you can use the following code:
$.ajax({
url: 'http://207.254.40.122/deetab/json.json',
dataType: 'json',
crossDomain: true
}).done(function(data){
console.log(data);// Check here whether sever send data or not
var res = data.city.filter(function(item){
return item.city_name =='City A';
});
//console.log(res);
var HTML = '<span>'+res[0].city_name+'</span>';
$('#title').append(HTML)
HTML = '<span>'+res[0].id+'</span>';
$('#id').append(HTML);;
HTML = '<span>'+res[0].year+'</span>';
$('#year').append(HTML);
});
You could add a filter to your $.each to check if the city id is the one you want.
$.each(data.city, function (i, city) {
if (city.id === 4)
HTML += '<span>' + city.city_name + '</span>';
});
Can prepare a filter with your desired city name and apply it to your data array to filter data preferred by you as in example:
var cities = {
"city": [{
"id": "4",
"year": "2014",
"city_name": "City A"
}, {
"id": "5",
"year": "2014",
"city_name": "City B"
}, {
"id": "6",
"year": "2014",
"city_name": "City C"
}]
};
//Want only city with this name
var filter = "City A";
console.log(cities.city);
cities.city = cities.city.filter(function(obj) {
return obj.city_name == filter;
});
console.log(cities.city);

Json, get info within another level

I have json code that comes out like:
{
"player": [{
"player_id": "1",
"player_name": "Maxfly",
"player_image": "res_573fc05f57c0e.png",
"player_background_image": "images/player_backgrounds/581046687fd89.jpg",
"player_info": "",
"player_region": "North America",
"player_teams": [{
"id": "1",
"team_name": "Test Team",
"team_link": "test-team"
}, {
"id": "65",
"team_name": "Test Team 2",
"team_link": "test-team-2"
}]
}]
}
I've managed to get the player_id and player_name etc. My question is how to I just get the teams? I've tried the following:
$.getJSON("jsonlink",
function(data) {
$.each(data.player.player_teams, function(i,player_team){
var append_data = "<div class='item team_item'><div class='row'><div class='col col_img'><a href='/t/" + player_team.team_name + "' ></a></div></div></div>";
$("#popin-container").append($('<div>' + append_data + '</div>').hide().fadeIn(800));
});
});
Trying to figure out what I'm doing wrong. Is my json object correct?
Thanks!
Your data.player.player_teams is wrong, as data.player is an array, and not an object. You need to loop through it, or in simple way, you need to attach a [0] like this:
$.each(data.player[0].player_teams, function(i, player_team) {

SAP UI5 Json Model Count

i have the following Problem. Sorry for my bad english that way.
I want to read a jsonfile and count the Number of Persons in it.
This result i will write to an variable.This variable is connected to the TileContainer. So when i write an new entry in my Json File i want that the TileContainer number is increased to.
Here my Code from my Company.json File:
{
"mitarbeiter": [
{ "Lastname": "Mustermann",
"Firstname": "Max",
"icon": "sap-icon://globe",
"adress": "Essen",
"geschlecht": "männlich",
"plz": "42222",
"street": "Viehoferplatz 11",
"jobinfo": "Softwareentwickler"
},
{ "Lastname": "Fischer",
"Firstname": "Elke",
"icon": "sap-icon://globe",
"adress": "Hamburg",
"geschlecht": "weiblich",
"plz": "31441",
"street": "Am Fischmarkt 12",
"jobinfo": "Verwaltungsassistentin"
},
{ "Lastname": "Mustermann",
"Firstname": "Heike",
"icon": "sap-icon://globe",
"adress": "Essen",
"geschlecht": "weiblich",
"plz": "42222",
"street": "Viehoferplatz 11",
"jobinfo": "Vorstandsvorsitzende"
}
]
}
on my controller.js
onInit: function() {
this.getView().addDelegate({onBeforeShow: function(evt) {
if (this.direction != "back") {
var model = new sap.ui.model.json.JSONModel();
model.loadData("JsonModels/Company.json");
alert(model.getJSON());
var XYZ;
var jsonModel =
{
"Tiles":[
{"Tile":
{ id : "idModelTile1",
title : "Mitarbeiter",
info: "Mitarbeiterdaten",
icon:"sap-icon://company-view",
activeIcon:"inbox",
number: XYZ,
appto: "idListPage"
//numberUnit: "positions"
},
}, ......
I want that the variable XYZ gets the Length Value, bevor the TileContainer is rendered. So the Number of Company-Employess is given on the Selectionscreen View.
Hope some one can help me. I make some implementations with jquery and so but nothing really work fine.
Dear,
Christian
When i add
alert(model.getProperty("/mitarbeiter/length"));
i get the alert message "undefined"...
Since the length property of an array can be read, you could simply use
var XYZ = model.getProperty("/mitarbeiter/length");
EDIT: here's a code example for the comment I gave below
onInit: function() {
jQuery.ajax({
url: "JsonModels/Company.json",
dataType: "json",
success: function(data, textStatus, jqXHR) {
var mitarbeiterCount = data.length;
var oTileModel = new sap.ui.model.json.JSONModel();
oTileModel.setData({
tiles :[{
tile : {
id : "idModelTile1",
title : "Mitarbeiter",
info : "Mitarbeiterdaten",
icon :"sap-icon://company-view",
activeIcon:"inbox",
number : mitarbeiterCount,
appto : "idListPage"
},
}]
});
sap.ui.getCore().setModel(oTileModel);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Oh no, an error occurred");
}
});
}
In your view, if you now bind your tile's number property, it should automagically work:
var oTileTemplate = new sap.m.StandardTile({
icon : "{icon}",
number : "{number}",
numberUnit: "mitarbeiter",
title : "{title}",
info : "{info}"
});
var oTileContainer = new sap.m.TileContainer().bindAggregation("tiles", "/", oTileTemplate);
//Etc...

Facebook looping through returned JSON Open Graph request

Im currently requesting the Open Graph url through JSON like so:
https://graph.facebook.com/me/friends?fields=email,likes,name,birthday,location,website&access_token=$token
My JSON request is succesful, however my issue is to actually loop through the returned data, so that I can list it on my page.
I've tried with the following:
$('#goButton').click(function () {
//Call the JSON feed from the Open Social Graph.
$.getJSON("https://graph.facebook.com/me/friends?fields=email,likes,name,birthday,location,website&access_token=" + savedFbToken + "&callback=?",
//Once it is returned, do something with the JSON:
function (data) {
console.log(data);
//Clear out the placeholder
$('#Placeholder').html("");
//Add some new data
$('#Placeholder').append("<h1>Name:</h1>" + data.name + "");
$('#Placeholder').append("<span>Birthday: "+ data.birthday +"</span><br/>");
$('#Placeholder').append("<span>Location: "+ data.location +"</span><br/>");
$('#Placeholder').append("<span>Id: "+ data.id +"</span><br/><br/>");
});
});
The format returned looks like this:
{
"data": [
{
"name": "Name 1",
"birthday": "10/08/1983",
"location": {
"id": "110343502319180",
"name": "Copenhagen, Denmark"
},
"id": "263901486"
},
{
"name": "Name 2",
"birthday": "02/16/1982",
"location": {
"id": "110398488982884",
"name": "Reykjav\u00edk, Iceland"
},
"id": "502533736"
},
etc...
Any suggestions on how to loop through this correctly?
data actually contains an object with an array of objects also named data, so you would need to loop through that
$('#Placeholder').html("");
for( var i = 0; i < data.data.length; i++ ){
//Add some new data
$('#Placeholder').append("<br />");
$('#Placeholder').append("<h1>Name:</h1>" + data.data[i].name + "");
$('#Placeholder').append("<span>Birthday: "+ data.data[i].birthday +"</span><br/>");
$('#Placeholder').append("<span>Location: "+ data.data[i].location +"</span><br/>");
$('#Placeholder').append("<span>Id: "+ data.data[i].id +"</span><br/><br/>");
}

Mixed array with json - parsing issue

I am doing a youtube api call, and I get back a var result = JSON.stringify(response, '', 2); which looks like :
{
"kind": "youtube#searchListResponse",
"pageInfo": {
"totalResults": 1000000,
"resultsPerPage": 5
},
"items": [
{
"id": {
"kind": "youtube#video",
"videoId": "DEne4AoX_RU"
},
"kind": "youtube#searchResult",
"snippet": {
"publishedAt": "2012-11-22T22:36:15.000Z",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/DEne4AoX_RU/default.jpg"
},
"medium": {
"url": "https://i.ytimg.com/vi/DEne4AoX_RU/mqdefault.jpg"
},
"high": {
"url": "https://i.ytimg.com/vi/DEne4AoX_RU/hqdefault.jpg"
}
}
}
},
{
"id": {...}
The full object response returns correctly in my console but I want to retrieve thumbnails url and display it as an li-tagged html list
So I tried first to fetch in a list all the snippet entries :
var obj = $.parseJSON(result);
$.each(obj, function() {
output += this.snippet + + "<br/>";
});
console.log(output);
But I have an message in my console : Uncaught TypeError: Cannot read property 'length' of undefined. What am I missing ? Btw, I don't understand why there are still brackets in the json stringified result (if someone could advise some good doc to understand how to parse JSON, would be great:))
You should be looping over items:
$.each(obj.items, function() {
output += this.snippet ...
});
What you receive is JSON, you shouldn't stringify it.
Remove this line
var result = JSON.stringify(response, '', 2);
and simply do
var obj = $.parseJSON(response);
you want to iterate over items,
snippet is an object literal,
+ + is not valid javascript.

Categories

Resources