Convert JSON Object to a simple array [closed] - javascript

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.

Related

Looping through items in an object for google sheets

I am trying to loop through an array that is part of a JSON object from a page speed insights call to add all of the unused javascript Urls to a google sheet using the script editor.
Here is an example of the JSON object:
"audits": {
"unused-javascript": {
"id": "unused-javascript",
"title": "Remove unused JavaScript",
"description": "Remove unused JavaScript to reduce bytes consumed by network activity. [Learn more](https://web.dev/unused-javascript/).",
"score": 0.43,
"scoreDisplayMode": "numeric",
"numericValue": 1350,
"numericUnit": "millisecond",
"displayValue": "Potential savings of 231 KiB",
"details": {
"type": "opportunity",
"headings": [
{
"key": "url",
"valueType": "url",
"subItemsHeading": {
"key": "source",
"valueType": "code"
},
"label": "URL"
},
{
"key": "totalBytes",
"valueType": "bytes",
"subItemsHeading": {
"key": "sourceBytes"
},
"label": "Transfer Size"
},
{
"key": "wastedBytes",
"valueType": "bytes",
"subItemsHeading": {
"key": "sourceWastedBytes"
},
"label": "Potential Savings"
}
],
"items": [
{
"url": "https://connect.facebook.net/signals/config/1926350194273730?v=2.9.2=stable",
"totalBytes": 140229,
"wastedBytes": 108197,
"wastedPercent": 77.15757011763822
},
{
"url": "https://static.example.com/domain.us.modern.bundle.a02fef045566caf5d464.js",
"totalBytes": 306716,
"wastedBytes": 106243,
"wastedPercent": 34.63892414884589
},
{
"url": "https://www.googletagmanager.com/gtm.js?id=GTM-KZ",
"totalBytes": 127214,
"wastedBytes": 21845,
"wastedPercent": 17.17151000374831
}
],
"overallSavingsMs": 1350,
"overallSavingsBytes": 236285
}
},
I am attempting to loop through the "items" array within the "unused-javascript" object and get all of the urls to show in google sheets.
Here is the code I have within the script editor. When I run this, only one URL shows on the sheet. However, I am trying to get all of the URLs added to the sheet.
function pageSpeed(Url) {
var key = "AIzaSyAyHY";
var serviceUrl = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=" + Url + "&key=" + key;
var array = [];
if (key == "YOUR_API_KEY")
return "Please enter your API key to the script";
var response = UrlFetchApp.fetch(serviceUrl);
if (response.getResponseCode() == 200) {
var content = JSON.parse(response.getContentText());
if ((content != null) && (content["lighthouseResult"] != null)) {
if (content["captchaResult"]) {
var timetointeractive = content["lighthouseResult"]["audits"]["interactive"]["displayValue"].slice(0, -2);
var firstcontentfulpaint = content["lighthouseResult"]["audits"]["first-contentful-paint"]["displayValue"].slice(0, -2);
var firstmeaningfulpaint = content["lighthouseResult"]["audits"]["first-meaningful-paint"]["displayValue"].slice(0, -2);
var speedindex = content["lighthouseResult"]["audits"]["speed-index"]["displayValue"].slice(0, -2);
var unusedJs = content["lighthouseResult"]["audits"]["unused-javascript"]["details"]["items"];
for (var i = 0; i < unusedJs.items.length; i++) {
var unusedUrl;
unusedUrl = unusedJs[i]["url"]
}
}
else {
var timetointeractive = "An error occured";
var firstcontentfulpaint = "An error occured";
var firstmeaningfulpaint = "An error occured";
var speedindex = "An error occured";
var unusedJs = "An error occured";
}
}
var currentDate = new Date().toJSON().slice(0, 10).replace(/-/g, '/');
array.push([timetointeractive, firstcontentfulpaint, firstmeaningfulpaint, speedindex, currentDate, "complete", unusedUrl]);
Utilities.sleep(1000);
return array;
}
}
Any and all help is appreciated!
You're on the right track.
Take a look below at my usage of Array.prototype.map. That's the simpler route.
Your for loop would work just as well IF you declared unusedUrl outside of (ie. before) the loop AND pushed to an existing array. As it is, there's an issue of scope, so unusedUrl is redeclared on every iteration, meaning you'll only assign the last iteration's value to unusedUrl.
Both solutions are below.
Using map
var content = {
lighthouseResult: {
audits: {
'unused-javascript': {
// Other stuff
details: {
// Other stuff
items: [
{
url:
'https://connect.facebook.net/signals/config/1926350194273730?v=2.9.2=stable',
totalBytes: 140229,
wastedBytes: 108197,
wastedPercent: 77.15757011763822,
},
{
url:
'https://static.example.com/domain.us.modern.bundle.a02fef045566caf5d464.js',
totalBytes: 306716,
wastedBytes: 106243,
wastedPercent: 34.63892414884589,
},
{
url: 'https://www.googletagmanager.com/gtm.js?id=GTM-KZ',
totalBytes: 127214,
wastedBytes: 21845,
wastedPercent: 17.17151000374831,
},
],
overallSavingsMs: 1350,
overallSavingsBytes: 236285,
},
},
},
},
}
var items = content.lighthouseResult.audits['unused-javascript'].details.items
var unusedUrls = items.map(item => item.url) // OR, using es6, items.map(({ url }) => url)
console.log(unusedUrls)
Using for
var items = content.lighthouseResult.audits['unused-javascript'].details.items
var unusedUrls = []
for (var i = 0; i < items.length; i++) {
unusedUrls.push(items[i]['url'])
}

How do I access an object in json?

I have a json structured like this:
{
"total": 4367,
"page": 1,
"per_page": 10,
"paging": {
"next": "/videos?query=second%20world%20war&per_page=10&access_token=XXX&page=2",
"previous": null,
"first": "/videos?query=second%20world%20war&per_page=10&access_token=XXX&page=1",
"last": "/videos?query=second%20world%20war&per_page=10&access_token=XXX&page=437"
},
"data": [
{
"uri": "/videos/128373915",
"name": "The Fallen of World War II",
I need to access name and I tried:
$.ajax( {
type: "GET",
url: url,
dataType: 'json',
success: vimeoResultsFunc
});
function vimeoResultsFunc(data){
for (var i = 0; i < data.length; i++) {
console.log(data[i].name);
}
}
But i get nothing
You're missing a level there. The vimeoResultsFunc will receive the top level object, then you have an array called data. Based on what you have it should be
function vimeoResultsFunc(data){
for (var i = 0; i < data.data.length; i++) {
console.log(data.data[i].name);
}
}
In the function vimeoResultsFunc(data) just add console.log(data) and see what is inside the data object. Probably this object does not have the structure you expect.

Deleting a key in JSON while making ajax call from 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.

How to iterate through deeply nested objects inside of a JSON?

I know there are plenty of questions about iterating through JSON objects but I haven't found one that quite relates to my exact problem. This is the JSON that I'm trying to iterate through:
psinsights = {
"kind": "pagespeedonline#result",
"id": "/speed/pagespeed",
"responseCode": 200,
"title": "PageSpeed Home",
"score": 90,
"pageStats": {
"numberResources": 22,
"numberHosts": 7,
"totalRequestBytes": "2761",
"numberStaticResources": 16,
"htmlResponseBytes": "91981",
"cssResponseBytes": "37728",
"imageResponseBytes": "13909",
"javascriptResponseBytes": "247214",
"otherResponseBytes": "8804",
"numberJsResources": 6,
"numberCssResources": 2
},
"formattedResults": {
"locale": "en_US",
"ruleResults": {
"AvoidBadRequests": {
"localizedRuleName": "Avoid bad requests",
"ruleImpact": 0.0
},
"MinifyJavaScript": {
"localizedRuleName": "Minify JavaScript",
"ruleImpact": 0.1417,
"urlBlocks": [
{
"header": {
"format": "Minifying the following JavaScript resources could reduce their size by $1 ($2% reduction).",
"args": [
{
"type": "BYTES",
"value": "1.3KiB"
},
{
"type": "INT_LITERAL",
"value": "0"
}
]
},
"urls": [
{
"result": {
"format": "Minifying $1 could save $2 ($3% reduction).",
"args": [
{
"type": "URL",
"value": "http://code.google.com/js/codesite_tail.pack.04102009.js"
},
{
"type": "BYTES",
"value": "717B"
},
{
"type": "INT_LITERAL",
"value": "1"
}
]
}
},
{
"result": {
"format": "Minifying $1 could save $2 ($3% reduction).",
"args": [
{
"type": "URL",
"value": "http://www.gmodules.com/ig/proxy?url\u003dhttp%3A%2F%2Fjqueryjs.googlecode.com%2Ffiles%2Fjquery-1.2.6.min.js"
},
{
"type": "BYTES",
"value": "258B"
},
{
"type": "INT_LITERAL",
"value": "0"
}
]
}
}
]
}
]
},
"SpriteImages": {
"localizedRuleName": "Combine images into CSS sprites",
"ruleImpact": 0.0
}
}
},
"version": {
"major": 1,
"minor": 11
}
};
Now, I'm trying to write a function that iterates through all of the ruleResults objects and returns an array of the localizedRuleName properties. According to the JSON, ruleResults has three member objects (AvoidBadRequests, MinifyJavaScript, and SpriteImages). Each of these has a localizedRuleName property I'm trying to access, but when I print out my array, it's blank. Here's how I've written my function:
function ruleList(results) {
var ruleArray = [];
for(var ruleName in results.formattedResults.ruleResults){
ruleArray[counter] = results.formattedResults.ruleResults[ruleName].localizedRuleName;
}
return ruleArray;
}
console.log(ruleList(psinsights));
Can you guys help me get on the right track? I used basically this same method to iterate through the pageStats of the JSON and it worked perfectly. I'm not sure why I can't get it to work with these deeper nested objects and properties.
your problem is not your iteration, but your undefined variable "counter".
Instead of using a counter can use the "push" function:
function ruleList(results) {
var ruleArray = [];
for(var ruleName in results.formattedResults.ruleResults){
ruleArray.push(results.formattedResults.ruleResults[ruleName].localizedRuleName);
}
return ruleArray;
}
fiddle: https://jsfiddle.net/fo9h56gh/
Hope this helps.
you're probably getting a javascript error since counter is not defined. you can try this:
function ruleList(results) {
var ruleArray = [];
var counter = 0;
for(var ruleName in results.formattedResults.ruleResults){
ruleArray[counter] = results.formattedResults.ruleResults[ruleName].localizedRuleName;
counter++;
}
return ruleArray;
}

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"
}
]

Categories

Resources