Deleting a key in JSON while making ajax call from javascript - javascript

I am new to java script and ajax. I have a JSON and I want to remove outputs cell in this JSON:
{
"cells": [{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "print(\"hi\")",
"execution_count": 1,
"outputs": [{
"output_type": "stream",
"text": "hi\n",
"name": "stdout"
}]
},
{
"metadata": {
"trusted": true,
"collapsed": true
},
"cell_type": "code",
"source": "",
"execution_count": null,
"outputs": []
}
],
"metadata": {
"kernelspec": {
"name": "Python [Root]",
"display_name": "Python [Root]",
"language": "python"
},
"anaconda-cloud": {},
"language_info": {
"pygments_lexer": "ipython3",
"version": "3.5.0",
"codemirror_mode": {
"version": 3,
"name": "ipython"
},
"mimetype": "text/x-python",
"file_extension": ".py",
"name": "python",
"nbconvert_exporter": "python"
},
"gist": {
"id": "",
"data": {
"description": "Untitled5.ipynb",
"public": true
}
}
},
"nbformat": 4,
"nbformat_minor": 0
}
and this is my attempt on removing the outputs cell. This piece of code posts the data to above mentioned JSON:
"use strict";
function _objectWithoutProperties(obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
}
var outputs = data.cells;
var data_dup = _objectWithoutProperties(data, ["outputs"]);
var id_input = $('#gist_id');
var id = params.gist_it_personal_access_token !== '' ? id_input.val() : '';
var method = id ? 'PATCH' : 'POST';
// Create/edit the Gist
$.ajax({
url: 'https://api.github.com/gists' + (id ? '/' + id : ''),
type: method,
dataType: 'json',
data: JSON.stringify(data_dup),
beforeSend: add_auth_token,
success: gist_success,
error: gist_error,
complete: complete_callback
});
};
But this code doesnt work. Can some one please guide how can we directly strip a key(outputs in this case) from ajax call and post it to JSON.
This is a gist extension of jupyter notebook and I am trying to strip output while posting it to gist on github

function _objectWithoutProperties(obj, key="outputs") { obj.cells.forEach(cell=>delete(cell[key])); }

If you use ES6, you can use this syntax to remove outputs:
{
...data,
cells: data.cells.map(({ outputs, ...otherProps }) => otherProps),
}
Note: data is your complete object.

Related

Parsing JSON into Google spreadsheet (Apps Script)

I have a download in JSON format that I get through the API.
Example:
{
"Employees": [
{
"User": {
"UserId": "4d132227-ea5c-4e57-b105-2f8b97872545",
"Login": "test#gmail.com",
"FullName": {
"LastName": "Фамилия",
"FirstName": "Имя",
"MiddleName": "Отчество"
},
"IsRegistered": true
},
"Permissions": {
"UserDepartmentId": "b5072e57-1e96-490b-ae03-2fd52ef84a3a",
"IsAdministrator": false,
"DocumentAccessLevel": "SelectedDepartments",
"SelectedDepartmentIds": [
"b5072e57-1e96-490b-ae03-2fd52ef84a3a",
"cd2e04dc-8d3f-4d63-88fd-f900c496e146",
"36e4434b-519d-4e40-9253-3464c10ed83e"
],
"Actions": [
{
"Name": "CreateDocuments",
"IsAllowed": true
},
{
"Name": "DeleteRestoreDocuments",
"IsAllowed": true
},
{
"Name": "SignDocuments",
"IsAllowed": true
},
{
"Name": "AddResolutions",
"IsAllowed": true
},
{
"Name": "RequestResolutions",
"IsAllowed": true
},
{
"Name": "ManageCounteragents",
"IsAllowed": false
}
],
"AuthorizationPermission": {
"IsBlocked": false
}
},
"Position": "Специалист по снабжению",
"CanBeInvitedForChat": true,
"CreationTimestamp": {
"Ticks": 637284074150000000
}
}
],
"TotalCount": 214
}
An example of what should happen:
enter image description here
The ratio of the JSON list of employees with columns in the table:
A: "User": {"UserId"} - Employee ID
B: "User": {""FullName""} - FULL NAME
C: "Position" - Position
D: "User": {"Login"} - Mail
E: "User": {"IsRegistered"} - Login activated?
F: "Permissions": {"IsAdministrator"} - Administrator?
G: "Permissions": {"Actions": [{"Name": "SignDocuments","isAllowed": true} - Can sign documents
H: "Permissions": {"Actions": [{"Name": "AddResolutions","isAllowed": true} - Can coordinate documents
I: "Permissions": {"Actions": [{"Name": "RequestResolutions","isAllowed": true} - Can request document approval
J: "Permissions": {"Actions": [{"Name": "CreateDocuments","isAllowed": true} - Can create documents and work with drafts
K: "Permissions": {"Actions": [{"Name": "DeleteRestoreDocuments","isAllowed": true} - Can delete documents and drafts, restore documents
L: "Permissions": {"Actions": [{"Name": "ManageCounteragents","isAllowed": true} - Can work with a list of counterparties
How can I convert JSON to a Google spreadsheet for 300+ rows? At the moment I only have a request to the API. The response is JSON. What are my next steps?
function GetEmployees(){
var DdocAuthKey = GetAuthToken()
for (let i = 0; i < boxId.length; i++) {
let url = `https://diadoc-api.kontur.ru/GetEmployees?boxId=`+ boxId[i]
let options =
{
method: "GET",
contentType: 'application/json',
headers: {authorization: "DiadocAuth ddauth_api_client_id=" + DdocAPIkey + `,ddauth_token=` + DdocAuthKey}
}
var json = UrlFetchApp.fetch(url, options)
var obj = JSON.parse(json)
printValues(obj);enter code here
}
}
function printValues(obj) {
for(var k in obj) {
if(obj[k] instanceof Object) {
printValues(obj[k]);
} else {
return obj[k] + "<br>"
}
}
}
This is the final version of the code. I hope this will help developers on JS and Apps Script when working with the Diadoc API.
Due to the fact that I have 3 organizations, I need to do an additional cycle:
for (let i = 0; i < boxId.length; i++)
If necessary, this cycle can be removed.
function GetEmployees() {
clearOrgSheets()
var DdocAuthKey = GetAuthToken()
let options =
{
method: "GET",
contentType: 'application/json',
headers: {authorization: "DiadocAuth ddauth_api_client_id=" + DdocAPIkey + `,ddauth_token=` + DdocAuthKey}
}
for (let i = 0; i < boxId.length; i++) {
let sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SheetNames[i])
let pageNum = 1
do {
let url = `https://diadoc-api.kontur.ru/GetEmployees?boxId=`+ boxId[i] + `&page=` + pageNum + `&count=50`
pageNum++
var obj = JSON.parse(UrlFetchApp.fetch(url, options))
var table = []; // it will be the 2d array
for (var employee of obj.Employees) {
var {LastName, FirstName, MiddleName} = employee.User.FullName;
var name = [LastName, FirstName, MiddleName].join(' ').trim();
var actions = {};
employee.Permissions.Actions.forEach(a => actions[a.Name] = a.IsAllowed);
var row =
[
employee.User.UserId,
name,
employee.Position,
employee.User.Login,
employee.User.IsRegistered,
employee.Permissions.IsAdministrator,
actions.SignDocuments, // Can sign documents
actions.AddResolutions, // Can coordinate documents
actions.RequestResolutions, // Can request document approval
actions.CreateDocuments, // Can create documents and work with drafts
actions.DeleteRestoreDocuments, // Can delete documents and drafts, restore documents
actions.ManageCounteragents, // Can work with a list of counterparties
];
table.push(row);
}
let lastRow = sheet.getLastRow() + 1
try{
let range = sheet.getRange(lastRow, 1, table.length, table[0].length )
range.setValues(table);
} catch (err){
break
}
} while (obj.Employees.length > 0);
}
}
Try this:
function myFunction() {
// here is your object (parsed json)
var obj = {
"Employees": [
{
"User": {
"UserId": "4d132227-ea5c-4e57-b105-2f8b97872545",
"Login": "test#gmail.com",
"FullName": {
"LastName": "Фамилия",
"FirstName": "Имя",
"MiddleName": "Отчество"
},
"IsRegistered": true
},
"Permissions": {
"UserDepartmentId": "b5072e57-1e96-490b-ae03-2fd52ef84a3a",
"IsAdministrator": false,
"DocumentAccessLevel": "SelectedDepartments",
"SelectedDepartmentIds": [ "b5072e57", "cd2e04dc", "36e4434b" ],
"Actions": [
{ "Name": "CreateDocuments", "IsAllowed": true },
{ "Name": "DeleteRestoreDocuments", "IsAllowed": true },
{ "Name": "SignDocuments", "IsAllowed": true },
{ "Name": "AddResolutions", "IsAllowed": true },
{ "Name": "RequestResolutions", "IsAllowed": true },
{ "Name": "ManageCounteragents", "IsAllowed": false }
],
"AuthorizationPermission": { "IsBlocked": false }
},
"Position": "Специалист по снабжению",
"CanBeInvitedForChat": true,
"CreationTimestamp": { "Ticks": 637284074150000000 }
}
],
"TotalCount": 214
};
var table = []; // it will be the 2d array
for (var employee of obj.Employees) {
var {LastName, FirstName, MiddleName} = employee.User.FullName;
var name = [LastName, FirstName, MiddleName].join(' ');
var actions = {};
employee.Permissions.Actions.forEach(a => actions[a.Name] = a.IsAllowed);
var row = [
employee.User.UserId,
name,
employee.Position,
employee.User.Login,
employee.User.IsRegistered,
employee.Permissions.IsAdministrator,
actions.SignDocuments, // Can sign documents
actions.AddResolutions, // Can coordinate documents
actions.RequestResolutions, // Can request document approval
actions.CreateDocuments, // Can create documents and work with drafts
actions.DeleteRestoreDocuments, // Can delete documents and drafts, restore documents
actions.ManageCounteragents, // Can work with a list of counterparties
];
table.push(row); // add the row to the 2d array
}
// put the 2d array on the sheet
SpreadsheetApp.getActiveSheet()
.getRange(2,1,table.length,table[0].length)
.setValues(table);
}
Let me know if it works.

How to add external data to javascript for jquery auto complete

I'm trying to make a auto complete search bar using jquery autocomplete. The thing is I need to display Json data from an external site into my search bar.
Whenever I try to put the data as such from json into the script, it's working. But when I refer external url it refuses to work.
I tried implementing all json data into my script. But it takes so long to process as there will be more than 40000+ lines in my html page.
The Json link for the data which I have to display is here
<script>
$('#id_ticker').autocomplete({
source: function(request, response) {
var data = {
"success": true,
"data": [
{
"symbol": "AACG",
"name": "ATA Creativity Global American Depositary Shares",
"lastsale": "$2.19",
"netchange": "-0.45",
"pctchange": "-17.045%",
"volume": "1408435",
"marketCap": "68715455.00",
"country": "China",
"ipoyear": "",
"industry": "Service to the Health Industry",
"sector": "Miscellaneous",
"url": "/market-activity/stocks/aacg"
},
{
"symbol": "AACI",
"name": "Armada Acquisition Corp. I Common Stock",
"lastsale": "$9.88",
"netchange": "0.01",
"pctchange": "0.101%",
"volume": "8345",
"marketCap": "204609860.00",
"country": "United States",
"ipoyear": "2021",
"industry": "",
"sector": "",
"url": "/market-activity/stocks/aaci"
}],
"additional_data": {
"pagination": {
"start": 0,
"limit": 5,
"more_items_in_collection": true,
"next_start": 5
}
}
};
var datamap = data.data.map(function(i) {
return {
label: i.symbol + ' - ' + i.name.split(' ').slice(0, 2).join(' '),
value: i.symbol,
desc: i.title
}
});
var key = request.term;
datamap = datamap.filter(function(i) {
return i.label.toLowerCase().indexOf(key.toLowerCase()) >= 0;
});
response(datamap);
},
minLength: 1,
delay: 500
});
</script>
The above code works and the below code doesn't.
<script>
$('#id_ticker').autocomplete({
source: function(request, response) {
var data = {
"success": true,
"data": ["https://raw.githubusercontent.com/rreichel3/US-Stock-Symbols/main/nyse/nyse_full_tickers.json"
],
"additional_data": {
"pagination": {
"start": 0,
"limit": 5,
"more_items_in_collection": true,
"next_start": 5
}
}
};
var datamap = data.data.map(function(i) {
return {
label: i.symbol + ' - ' + i.name.split(' ').slice(0, 2).join(' '),
value: i.symbol,
desc: i.title
}
});
var key = request.term;
datamap = datamap.filter(function(i) {
return i.label.toLowerCase().indexOf(key.toLowerCase()) >= 0;
});
response(datamap);
},
minLength: 1,
delay: 500
});
</script>
Looking for a solution to add this and also for a solution to reduce the json key pair with only "symbol" and "name" from each corresponding data in the link.
Try this:
function toAutocomplete(dt, keyvar){
let rli = [];
for (let i = 0; i < dt.length; i++) rli.push(dt[i][keyvar]);
return rli;
}
function inArrayAutocompleteSelected(key, array_autocomplete, array_master){
let x = array_master[$.inArray(key, array_autocomplete)];
return x;
}
$('#id_ticker').autocomplete({ source: [], minLength: 1 });
// $('#id_ticker').autocomplete("disable");
let url = 'https://raw.githubusercontent.com/rreichel3/US-Stock-Symbols/main/nyse/nyse_full_tickers.json';
let r = _ajax('GET', url, ''); // your ajax script
console.log(r);
let liAuto = toAutocomplete(r, 'name');
console.log(liAuto);
$('#id_ticker').autocomplete("option", "source", liAuto );
// $('#id_ticker').autocomplete("enable");
$("#id_ticker").autocomplete({
select: function( event, ui ) {
console.log(ui, ui.item);
getData = inArrayAutocompleteSelected(ui.item.value, liAuto, r);
console.log(getData);
}
});

How can I avoid options if those options are previously selected in vue js html?

My json data for getting all inventories is
{
"status": true,
"data": [
{ "inv_id": 1, "name": "Arts" },
{ "inv_id": 2, "name": "web" },
{ "inv_id": 3, "name": "mobileapp" },
{ "inv_id": 4, "name": "ws" },
{ "inv_id": 5, "name": "aop" },
{ "inv_id": 6, "name": "bin" },
{ "inv_id": 7, "name": "webs" },
{ "inv_id": 8, "name": "hell" }
]
}
My json data which is selected already by user will be in the following format
{
"data": {
"pid": 109,
"contact": {
"email": "ew98#gmail.com",
"phone": 85998472,
"address": { "country": "India", "state": "Kerala" }
},
"about": "hello how are you",
"is_featured": false,
"avg_rating": 0,
"total_reviews": 0,
"reviews": [],
"inventory": [
{
"item": {
"name": "Arts",
"category": { "name": "Education", "id": 1 },
"id": 1
}
}
],
"review": null
},
"status": true
}
Here arts is already selected, so I need to avoid the same when I am giving an edit option. How can I able to achieve the same.
mounted() {
var self = this
data = {}
data["auth-token"] = this.authType
data["pid"] = this.pid
$.ajax({
url: "http://127.0.0.1:8000/get/post/",
data: data,
type: "POST",
dataType: "json",
success: function(e) {
if (e.status == 1) {
self.inventory = e.data.inventory
data = {}
data["category"] = self.catid
data["cat_id"] = self.catid
$.ajax({
url: "http://127.0.0.1:8000/alpha/get/inventory/",
data: data,
type: "POST",
dataType: "JSON",
success: function(e) {
if (e.status == 1) {
self.inventoryall = e.data
}
},
})
}
},
})
}
I have all inventories in inventoryall[] and inventory that is already added in inventory[].
My html code is
<div class="form-group">
<label>Inventory
<small>(required)</small>
</label>
<select
id="basic"
class="selectpicker"
data-live-search="true"
data-live-search-style="begins"
title="Select Your Subcategory"
v-model="inv" name="inv[]" multiple required="required"
>
<option v-for="sop in inventoryall" v-bind:value="sop.inv_id">{{sop.name}}</option>
</select>
</div>
So, when I display the inventories here, I need to avoid the once that is already selected. Please help me to have a solution.
Here you can use the array filter method:
// filter loops through every item in the array and returns a new array
// if the filter function returns true, the item stays in the new array
// if the filter function returns false, the item is removed
self.inventoryall = self.inventoryall.filter(item => {
// loop through all of the currently selected items
for (const selectedItem of self.inventory) {
// if we find a current item with the same ID as the selected one,
// return false, so we don't keep the item
if (selectedItem.id === item.inv_id) {
return false
}
}
// if we never find an item with a matching ID, return true to keep it
return true
})
Note that this method is only available in browsers that support ES6, so use the polyfill on the MDN page if you need to support older browsers.
Another note, since you're using Vue, this would probably be a good use case for a computed property.

C# ListItemCollection to JSON, while keeping values and text items

I have created a web service (asmx file) that returns a serialized ListItemCollection with the following code.
public string getStates(string Country)
{
ListItemCollection lic = DBInterface.GetStates(Country);
var serialized = JsonConvert.SerializeObject(lic);
return serialized;
}
I call the web service via javascript when a user selects a country from a dropdown list using the following code.
//ajax function that uses web services to get states
function GetStates(val)
{
$.ajax({
type: "POST",
url: "/WebServices/getServerData.asmx/getStates",
data: JSON.stringify({Country: val}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#ddlState").empty();
var parsed = JSON.parse(data.d);
for (var i = 0; i < parsed.length; i++) {
$("#ddlState").append("<option value='" + parsed[i] + "'>" + parsed[i] + "</option>");
}
},
error: function (data) {
alert(data.status + " " + data.statusText);
}
});
}
The issue is that I want to also keep not only the ListItemCollection text, but also it's value. However the "JsonConvert.SerializeObject only returns the text items. Can someone help to return the value and text so that I can populate the dropdown via javascript?
Thanks!
One thing you can use the JavaScriptSerializer() in System.Web.Script.Serialization:
ListItemCollection lic = new ListItemCollection() {
new ListItem("Display Text", "val1"),
new ListItem("Display Text 2", "val2"),
};
var ser = new JavaScriptSerializer();
var serialized = ser.Serialize(lic);
Results in (I took the liberty to format) :
[
{
"Attributes": {
"Keys": [],
"Count": 0,
"CssStyle": {
"Keys": [],
"Count": 0,
"Value": null
}
},
"Enabled": true,
"Selected": false,
"Text": "Display Text",
"Value": "val1"
},
{
"Attributes": {
"Keys": [],
"Count": 0,
"CssStyle": {
"Keys": [],
"Count": 0,
"Value": null
}
},
"Enabled": true,
"Selected": false,
"Text": "Display Text 2",
"Value": "val2"
}
]

Convert JSON Object to a simple array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have the following nested JSON Object coming from this call:
var jsonData = jQuery.ajax({
url: "http://testsite/_vti_bin/listdata.svc/ProjectHours",
dataType: "json",
async: false
}).responseText;
{
"d": {
"results": [
{
"__metadata": {
"uri": "http://testsite/_vti_bin/listdata.svc/ProjectHours(1)",
"etag": "W/\"1\"",
"type": "Microsoft.SharePoint.DataService.ProjectHoursItem"
},
"ContentTypeID": "0x0100C5D130A92A732D4C9E8489B50657505B",
"Title": "Ryan Cruz",
"Hours": 35,
"Id": 1,
"ContentType": "Item",
"Modified": "/Date(1373535682000)/",
"Created": "/Date(1373535682000)/",
"CreatedBy": {
"__deferred": {
"uri": "http://testsite/_vti_bin/listdata.svc/ProjectHours(1)/CreatedBy"
}
},
"CreatedById": 19,
"ModifiedBy": {
"__deferred": {
"uri": "http://testsite/_vti_bin/listdata.svc/ProjectHours(1)/ModifiedBy"
}
},
"ModifiedById": 19,
"Owshiddenversion": 1,
"Version": "1.0",
"Attachments": {
"__deferred": {
"uri": "http://testsite/_vti_bin/listdata.svc/ProjectHours(1)/Attachments"
}
},
"Path": "/sites/itg/Resourcecenters/spwidgets/Lists/ProjectHours"
},
{
"__metadata": {
"uri": "http://testsite/_vti_bin/listdata.svc/ProjectHours(2)",
"etag": "W/\"1\"",
"type": "Microsoft.SharePoint.DataService.ProjectHoursItem"
},
"ContentTypeID": "0x0100C5D130A92A732D4C9E8489B50657505B",
"Title": "Phillip Phillips",
"Hours": 25,
"Id": 2,
"ContentType": "Item",
"Modified": "/Date(1373535694000)/",
"Created": "/Date(1373535694000)/",
"CreatedBy": {
"__deferred": {
"uri": "http://testsite/_vti_bin/listdata.svc/ProjectHours(2)/CreatedBy"
}
},
"CreatedById": 19,
"ModifiedBy": {
"__deferred": {
"uri": "http://testsite/_vti_bin/listdata.svc/ProjectHours(2)/ModifiedBy"
}
},
"ModifiedById": 19,
"Owshiddenversion": 1,
"Version": "1.0",
"Attachments": {
"__deferred": {
"uri": "http://testsite/_vti_bin/listdata.svc/ProjectHours(2)/Attachments"
}
},
"Path": "/sites/itg/Resourcecenters/spwidgets/Lists/ProjectHours"
}
]
}
}
I want to loop through each object's Title and Hours attribute and save them in an array so I can pass it to the google chart as below:
var data = google.visualization.arrayToDataTable(array);
I tried the following code, but it can't find the json object:
function drawTable() {
var jsonData = jQuery.ajax({
url: "http://testsite/_vti_bin/listdata.svc/ProjectHours",
dataType: "json",
async: false
}).responseText;
alert(jsonData);
var obj = jQuery.parseJSON(jsonData);
//alert(jsonData.length);
var sampleData = [], results = d.results;
for (var i = 0, len = results.length; i < len; i++) {
var result = results[i];
sampleData.push({ Title: result.Title, Hours: result.Hours});
}
var data = google.visualization.arrayToDataTable(obj);
var chart = new google.visualization.PieChart(document.getElementById('spChart'));
chart.draw(data, {showRowNumber: true});
}
Please give me some ideas so i don't get stuck here for the rest of the day. Thank you!
jQuery.getJSON({"http://testsite/_vti_bin/listdata.svc/ProjectHours",{},function(d) {
var sampleData = [], results = d.results;
for (var i = 0, len = results.length; i < len; i++) {
var result = results[i];
sampleData.push({ Title: results[i].Title, Hours: results[i].Hours});
};
});
OK, I am answering my own question here in case someone runs across something similar.
This was an ajax call to a MS SharePoint site returning list data in JSON.
jQuery.ajax({
url: "http://testsite/_vti_bin/listdata.svc/ProjectHours",
dataType: 'JSON',
success:function(data) {
//jQuery('#spChart').append(JSON.stringify(json));
//var obj = jQuery.parseJSON(data);
var rowArray = [], results = data.d.results;
for (var i=0; i < results.length; i++)
{
var result = results[i];
rowArray.push([result.Title, result.Hours]);
//rowArray.push(["'" + result.Title + "'", result.Hours]);
}
},
error:function(){
alert("Error");
}
});
I had to first refer the json being returned as 'data' and access each javascript object inside of it as data.d.results[0], data.d.results[1], data.d.results[2] etc by looping through each of them.

Categories

Resources