Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) - javascript
I need some help with this error:
Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse ()
at Object.success (dashboard.js:22)
at fire (jquery-3.3.1.js:3268)
at Object.fireWith [as resolveWith] (jquery-3.3.1.js:3398)
at done (jquery-3.3.1.js:9305)
at XMLHttpRequest. (jquery-3.3.1.js:9548)
I try to transform a string to a json object using JSON.parse() that cause that error.
I am using oracleJet and this is my code:
function DashboardViewModel() {
var self = this;
self.lineTypeValue = ko.observable('curved');
var scatterSeries = [];
$.getJSON( "http://localhost:8080/points", function (data) {
console.info(data);
var ch = '{"name":"graphe1","items":'+JSON.stringify(data.results[1])+ '}';
console.info(ch);
console.info(JSON.parse(scatterSeries));
scatterSeries.push(JSON.parse(ch));
});
/* chart data */
this.scatterSeriesValue = ko.observableArray(scatterSeries);
self.lineTypeOptions = [
{id: 'straight', label: 'straight'},
{id: 'curved', label: 'curved'},
{id: 'stepped', label: 'stepped'},
{id: 'segmented', label: 'segmented'},
{id: 'none', label: 'none'}
];
}
The Json that I get from "http://localhost:8080/points" look like this:
{ "results":[
[
{
"b":"0.110547334",
"cost":"0.000000",
"w":"1.998889"
}
],
[
{
"x":0,
"y":0
},
{
"x":1,
"y":2
},
{
"x":2,
"y":4
},
{
"x":3,
"y":6
},
{
"x":4,
"y":8
},
{
"x":5,
"y":10
},
{
"x":6,
"y":12
},
{
"x":7,
"y":14
},
{
"x":8,
"y":16
},
{
"x":9,
"y":18
},
{
"x":10,
"y":20
},
{
"x":11,
"y":22
},
{
"x":12,
"y":24
},
{
"x":13,
"y":26
},
{
"x":14,
"y":28
},
{
"x":15,
"y":30
},
{
"x":16,
"y":32
},
{
"x":17,
"y":34
},
{
"x":18,
"y":36
},
{
"x":19,
"y":38
},
{
"x":20,
"y":40
},
{
"x":21,
"y":42
},
{
"x":22,
"y":44
},
{
"x":23,
"y":46
},
{
"x":24,
"y":48
},
{
"x":25,
"y":50
},
{
"x":26,
"y":52
},
{
"x":27,
"y":54
},
{
"x":28,
"y":56
},
{
"x":29,
"y":58
},
{
"x":30,
"y":60
},
{
"x":31,
"y":62
},
{
"x":32,
"y":64
},
{
"x":33,
"y":66
},
{
"x":34,
"y":68
},
{
"x":35,
"y":70
},
{
"x":36,
"y":72
},
{
"x":37,
"y":74
},
{
"x":38,
"y":76
},
{
"x":39,
"y":78
},
{
"x":40,
"y":80
},
{
"x":41,
"y":82
},
{
"x":42,
"y":84
},
{
"x":43,
"y":86
},
{
"x":44,
"y":88
},
{
"x":45,
"y":90
},
{
"x":46,
"y":92
},
{
"x":47,
"y":94
},
{
"x":48,
"y":96
},
{
"x":49,
"y":98
},
{
"x":50,
"y":100
},
{
"x":51,
"y":102
},
{
"x":52,
"y":104
},
{
"x":53,
"y":106
},
{
"x":54,
"y":108
},
{
"x":55,
"y":110
},
{
"x":56,
"y":112
},
{
"x":57,
"y":114
},
{
"x":58,
"y":116
},
{
"x":59,
"y":118
},
{
"x":60,
"y":120
},
{
"x":61,
"y":122
},
{
"x":62,
"y":124
},
{
"x":63,
"y":126
},
{
"x":64,
"y":128
},
{
"x":65,
"y":130
},
{
"x":66,
"y":132
},
{
"x":67,
"y":134
},
{
"x":68,
"y":136
},
{
"x":69,
"y":138
},
{
"x":70,
"y":140
},
{
"x":71,
"y":142
},
{
"x":72,
"y":144
},
{
"x":73,
"y":146
},
{
"x":74,
"y":148
},
{
"x":75,
"y":150
},
{
"x":76,
"y":152
},
{
"x":77,
"y":154
},
{
"x":78,
"y":156
},
{
"x":79,
"y":158
},
{
"x":80,
"y":160
},
{
"x":81,
"y":162
},
{
"x":82,
"y":164
},
{
"x":83,
"y":166
},
{
"x":84,
"y":168
},
{
"x":85,
"y":170
},
{
"x":86,
"y":172
},
{
"x":87,
"y":174
},
{
"x":88,
"y":176
},
{
"x":89,
"y":178
},
{
"x":90,
"y":180
},
{
"x":91,
"y":182
},
{
"x":92,
"y":184
},
{
"x":93,
"y":186
},
{
"x":94,
"y":188
},
{
"x":95,
"y":190
},
{
"x":96,
"y":192
},
{
"x":97,
"y":194
},
{
"x":98,
"y":196
},
{
"x":99,
"y":198
}
]]}
and what I want the variable scatterSeries to hold is a table like this one:
[ {
name:"graphe1",
items:[
{
x:8,
y:2
},
{
x:15,
y:15
},
{
x:25,
y:26
},
{
x:33,
y:22
},
{
x:36,
y:40
}
]},]
what I get in the console about the string ch is this:
{"name":"graphe1","items":[{"x":0,"y":0},{"x":1,"y":2},{"x":2,"y":4},{"x":3,"y":6},{"x":4,"y":8},{"x":5,"y":10},{"x":6,"y":12},{"x":7,"y":14},{"x":8,"y":16},{"x":9,"y":18},{"x":10,"y":20},{"x":11,"y":22},{"x":12,"y":24},{"x":13,"y":26},{"x":14,"y":28},{"x":15,"y":30},{"x":16,"y":32},{"x":17,"y":34},{"x":18,"y":36},{"x":19,"y":38},{"x":20,"y":40},{"x":21,"y":42},{"x":22,"y":44},{"x":23,"y":46},{"x":24,"y":48},{"x":25,"y":50},{"x":26,"y":52},{"x":27,"y":54},{"x":28,"y":56},{"x":29,"y":58},{"x":30,"y":60},{"x":31,"y":62},{"x":32,"y":64},{"x":33,"y":66},{"x":34,"y":68},{"x":35,"y":70},{"x":36,"y":72},{"x":37,"y":74},{"x":38,"y":76},{"x":39,"y":78},{"x":40,"y":80},{"x":41,"y":82},{"x":42,"y":84},{"x":43,"y":86},{"x":44,"y":88},{"x":45,"y":90},{"x":46,"y":92},{"x":47,"y":94},{"x":48,"y":96},{"x":49,"y":98},{"x":50,"y":100},{"x":51,"y":102},{"x":52,"y":104},{"x":53,"y":106},{"x":54,"y":108},{"x":55,"y":110},{"x":56,"y":112},{"x":57,"y":114},{"x":58,"y":116},{"x":59,"y":118},{"x":60,"y":120},{"x":61,"y":122},{"x":62,"y":124},{"x":63,"y":126},{"x":64,"y":128},{"x":65,"y":130},{"x":66,"y":132},{"x":67,"y":134},{"x":68,"y":136},{"x":69,"y":138},{"x":70,"y":140},{"x":71,"y":142},{"x":72,"y":144},{"x":73,"y":146},{"x":74,"y":148},{"x":75,"y":150},{"x":76,"y":152},{"x":77,"y":154},{"x":78,"y":156},{"x":79,"y":158},{"x":80,"y":160},{"x":81,"y":162},{"x":82,"y":164},{"x":83,"y":166},{"x":84,"y":168},{"x":85,"y":170},{"x":86,"y":172},{"x":87,"y":174},{"x":88,"y":176},{"x":89,"y":178},{"x":90,"y":180},{"x":91,"y":182},{"x":92,"y":184},{"x":93,"y":186},{"x":94,"y":188},{"x":95,"y":190},{"x":96,"y":192},{"x":97,"y":194},{"x":98,"y":196},{"x":99,"y":198}]}
Any help please?!! :( :(
You are calling:
JSON.parse(scatterSeries)
But when you defined scatterSeries, you said:
var scatterSeries = [];
When you try to parse it as JSON it is converted to a string (""), which is empty, so you reach the end of the string before having any of the possible content of a JSON text.
scatterSeries is not JSON. Do not try to parse it as JSON.
data is not JSON either (getJSON will parse it as JSON automatically).
ch is JSON … but shouldn't be. You should just create a plain object in the first place:
var ch = {
"name": "graphe1",
"items": data.results[1]
};
scatterSeries.push(ch);
In short, for what you are doing, you shouldn't have JSON.parse anywhere in your code. The only place it should be is in the jQuery library itself.
I was trying to debug this same error (I was writing code in TypeScript), but no matter what I did, the error didn't go away, it was really persistent.
I tried to look into the solution in many blogs and also this SO thread. I tried everything and nothing worked out.
Finally, I saw that I created the required file named products.json in which I gave a single extra newline (meaning, previously the file had 1 empty line, now it had 2 empty lines) and was following good GitHub practices as mentioned here.
Because of that single extra newline in my products.json file, I wasted 2 hours fixing a bug that didn't exist in the first place.
Finally when I deleted the entire products.json file and re-ran the entire thing, I didn't get any runtime errors and everything was running without any problems.
What I learned by going through all this?
It's that experience is the teacher of all things.
Remove this line from your code:
console.info(JSON.parse(scatterSeries));
Issue is with the Json.parse of empty array - scatterSeries , as you doing console log of scatterSeries before pushing ch
var data = { "results":[
[
{
"b":"0.110547334",
"cost":"0.000000",
"w":"1.998889"
}
],
[
{
"x":0,
"y":0
},
{
"x":1,
"y":2
},
{
"x":2,
"y":4
},
{
"x":3,
"y":6
},
{
"x":4,
"y":8
},
{
"x":5,
"y":10
},
{
"x":6,
"y":12
},
{
"x":7,
"y":14
},
{
"x":8,
"y":16
},
{
"x":9,
"y":18
},
{
"x":10,
"y":20
},
{
"x":11,
"y":22
},
{
"x":12,
"y":24
},
{
"x":13,
"y":26
},
{
"x":14,
"y":28
},
{
"x":15,
"y":30
},
{
"x":16,
"y":32
},
{
"x":17,
"y":34
},
{
"x":18,
"y":36
},
{
"x":19,
"y":38
},
{
"x":20,
"y":40
},
{
"x":21,
"y":42
},
{
"x":22,
"y":44
},
{
"x":23,
"y":46
},
{
"x":24,
"y":48
},
{
"x":25,
"y":50
},
{
"x":26,
"y":52
},
{
"x":27,
"y":54
},
{
"x":28,
"y":56
},
{
"x":29,
"y":58
},
{
"x":30,
"y":60
},
{
"x":31,
"y":62
},
{
"x":32,
"y":64
},
{
"x":33,
"y":66
},
{
"x":34,
"y":68
},
{
"x":35,
"y":70
},
{
"x":36,
"y":72
},
{
"x":37,
"y":74
},
{
"x":38,
"y":76
},
{
"x":39,
"y":78
},
{
"x":40,
"y":80
},
{
"x":41,
"y":82
},
{
"x":42,
"y":84
},
{
"x":43,
"y":86
},
{
"x":44,
"y":88
},
{
"x":45,
"y":90
},
{
"x":46,
"y":92
},
{
"x":47,
"y":94
},
{
"x":48,
"y":96
},
{
"x":49,
"y":98
},
{
"x":50,
"y":100
},
{
"x":51,
"y":102
},
{
"x":52,
"y":104
},
{
"x":53,
"y":106
},
{
"x":54,
"y":108
},
{
"x":55,
"y":110
},
{
"x":56,
"y":112
},
{
"x":57,
"y":114
},
{
"x":58,
"y":116
},
{
"x":59,
"y":118
},
{
"x":60,
"y":120
},
{
"x":61,
"y":122
},
{
"x":62,
"y":124
},
{
"x":63,
"y":126
},
{
"x":64,
"y":128
},
{
"x":65,
"y":130
},
{
"x":66,
"y":132
},
{
"x":67,
"y":134
},
{
"x":68,
"y":136
},
{
"x":69,
"y":138
},
{
"x":70,
"y":140
},
{
"x":71,
"y":142
},
{
"x":72,
"y":144
},
{
"x":73,
"y":146
},
{
"x":74,
"y":148
},
{
"x":75,
"y":150
},
{
"x":76,
"y":152
},
{
"x":77,
"y":154
},
{
"x":78,
"y":156
},
{
"x":79,
"y":158
},
{
"x":80,
"y":160
},
{
"x":81,
"y":162
},
{
"x":82,
"y":164
},
{
"x":83,
"y":166
},
{
"x":84,
"y":168
},
{
"x":85,
"y":170
},
{
"x":86,
"y":172
},
{
"x":87,
"y":174
},
{
"x":88,
"y":176
},
{
"x":89,
"y":178
},
{
"x":90,
"y":180
},
{
"x":91,
"y":182
},
{
"x":92,
"y":184
},
{
"x":93,
"y":186
},
{
"x":94,
"y":188
},
{
"x":95,
"y":190
},
{
"x":96,
"y":192
},
{
"x":97,
"y":194
},
{
"x":98,
"y":196
},
{
"x":99,
"y":198
}
]]};
var scatterSeries = [];
var ch = '{"name":"graphe1","items":'+JSON.stringify(data.results[1])+ '}';
console.info(ch);
scatterSeries.push(JSON.parse(ch));
console.info(scatterSeries);
code sample - https://codepen.io/nagasai/pen/GGzZVB
You define var scatterSeries = [];, and then try to parse it as a json string at console.info(JSON.parse(scatterSeries)); which obviously fails. The variable is converted to an empty string, which causes an "unexpected end of input" error when trying to parse it.
Encountered this error in the following function when I tried to pull 'nothing' from LS
Quick fix for posterity
const getUserFromLocalStorage = () => {
try {
return JSON.parse(localStorage.getItem('user') || '');
} catch (error) {
return null;
}
};
In my case, using .NET 6, the problem was that the controller was declared as void and did not return any value.
Simply changing the method declaration to int and adding return 0; solved this issue for me.
[HttpPost]
public int MyMethod(string text)
{
_logger.Log(text);
return 0;
}
This is because of the data that you are trying to parse is not in a parsable format .
so i suggest to check the data is parsable or not before define the parse.
const IsParsable = (data) => {
try {
JSON.parse(data);
} catch (e) {
return false;
}
return true;
}
var Obj= JSON.stringify({
"name": "graphe1",
"items": data.results[1]
})
return IsParsable (Obj) ? JSON.parse(Obj) : false
Related
Is there a way to get ProvisioningArtifactParameters in order specified in the CloudFormation template?
I am using AWS API(version 2015-12-10, javascript) to fetch Service Catalog products. describeProvisioningParameters method returns an object with ProvisioningArtifactParameters field which contains parameters, but these parameters sorted in a way different from the way provided in the CloudFormation template. Parameters part of CloudFormation template: { "Parameters": { "DBInputCIDR": { }, "DBName": { }, "DBPortNumber": { }, "DBMasterUsername": { }, "DBMasterUserPassword": { }, "DBBackupRetentionPeriod": { }, "DBAllocatedStorage": { }, "DBEngineVersion": { }, "DBInstanceClass": { }, "MultiAZ": { } } } Parameters part of API response: { "ProvisioningArtifactParameters": [ { "ParameterKey": "DBBackupRetentionPeriod" }, { "ParameterKey": "DBEngineVersion" }, { "ParameterKey": "DBPortNumber" }, { "ParameterKey": "DBAllocatedStorage" }, { "ParameterKey": "DBMasterUserPassword" }, { "ParameterKey": "DBInstanceClass" }, { "ParameterKey": "DBInputCIDR" }, { "ParameterKey": "DBMasterUsername" }, { "ParameterKey": "DBName" }, { "ParameterKey": "MultiAZ" } ] } Is there any way to sort API response as specified in CloudFormation template?
Convert multiple json object into array of object
My data is currently stored in this format: { "Site1":{ "week":[ { "access":1 }, { "access":8 } ] }, "Site2":{ "week":[ { "access":16 } ] }, "Site3":{ "week":[ { "access":2 }, { "access":6 }, { "access":2 } ] } } And I need to convert it into this format: [ { "id":"Site1", "access":[1,8] }, { "id":"Site2", "access":[16] }, { "id":"Site3", "access":[2,6,2] } ] As you can see, I also need to take the keys (site name) and make them the "id" values. Any ideas on how I can do this in JavaScript (I'm using angular v9)? I'm not very good at restructuring that type of data.
You can first take entries and then map it: var data={ "Site1":{ "week":[ { "access":1 }, { "access":8 } ] }, "Site2":{ "week":[ { "access":16 } ] }, "Site3":{ "week":[ { "access":2 }, { "access":6 }, { "access":2 } ] }}; var result = Object.entries(data).map(([k,v])=>({id:k, access: v.week.map(p=>p.access)})); console.log(result);
Object.keys() map() const data = { Site1: { week: [ { access: 1, }, { access: 8, }, ], }, Site2: { week: [ { access: 16, }, ], }, Site3: { week: [ { access: 2, }, { access: 6, }, { access: 2, }, ], }, }; const result = Object.keys(data).map(key => ({ id: key, access: data[key].week.map(w => w.access), })); console.log(result);
you can simply use this code for your desired result. Object.keys(data).map(key => ( { id: key, access: data[key].week.map(obj => obj.access), } )) Let me know if you face any issue.
How to parse Json and used nested loops
I have 2 sets of JSON data but I'm not sure how to use javascript and parse the information. API1, data stored in variable called response1: [{"placeid":1,"place_name":"arora-square","city":"miami","state":"florida","country":"US"}, {"placeid":2,"place_name":"hoover","city":"palo-alto","state":"california","country":"US"} API2, data stored in variable called response2: [ { "manufacturer":"apple", "market_name":"apple_market1", "codename":"xx", "model":"iphone", "usage_statistics":{ "session_infos":[ { "building_id":17, "purchases":[ { "item_id":9, "item_category_id":9, "cost":100 }, { "item_id":81, "item_category_id":6, "cost":300 }, { "item_id":197, "item_category_id":2, "cost":4 } ] }, { "building_id":18, "purchases":[ { "item_id":94, "item_category_id":4, "cost":150 }, { "item_id":126, "item_category_id":6, "cost":400 }, { "item_id":180, "item_category_id":0, "cost":300 } ] }, { "building_id":16, "purchases":[ { "item_id":78, "item_category_id":3, "cost":30 }, { "item_id":30, "item_category_id":0, "cost":101.77 }, { "item_id":103, "item_category_id":13, "cost":52.92 }, { "item_id":25, "item_category_id":10, "cost":106.87 }, { "item_id":161, "item_category_id":11, "cost":145.23 }, { "item_id":70, "item_category_id":10, "cost":19.32 }, { "item_id":113, "item_category_id":8, "cost":136.96 }, { "item_id":43, "item_category_id":13, "cost":115.86 }, { "item_id":59, "item_category_id":14, "cost":114.13 }, { "item_id":171, "item_category_id":6, "cost":46.61 } ] }, { "building_id":16, "purchases":[ { "item_id":39, "item_category_id":9, "cost":128.04 }, { "item_id":167, "item_category_id":2, "cost":65.36 }, { "item_id":190, "item_category_id":10, "cost":79.08 }, { "item_id":83, "item_category_id":8, "cost":116.38 }, { "item_id":153, "item_category_id":3, "cost":125.87 }, { "item_id":43, "item_category_id":13, "cost":115.86 }, { "item_id":114, "item_category_id":9, "cost":112.14 }, { "item_id":31, "item_category_id":1, "cost":136.3 }, { "item_id":8, "item_category_id":8, "cost":110.61 }, { "item_id":4, "item_category_id":4, "cost":80.13 } ] }, { "building_id":17, "purchases":[ { "item_id":117, "item_category_id":12, "cost":138.33 }, { "item_id":3, "item_category_id":3, "cost":82.21 }, { "item_id":6, "item_category_id":6, "cost":51.55 }, { "item_id":139, "item_category_id":4, "cost":132.47 } ] } ] } }, { "manufacturer":"Samsung", "market_name":"Galaxy S7 Edge", "codename":"hero2lte", "model":"SM-G935F", "usage_statistics":{ "session_infos":[ { "building_id":17, "purchases":[ { "item_id":137, "item_category_id":2, "cost":112.87 }, { "item_id":53, "item_category_id":8, "cost":140.45 }, { "item_id":21, "item_category_id":6, "cost":126.53 }, { "item_id":177, "item_category_id":12, "cost":130.49 }, { "item_id":41, "item_category_id":11, "cost":48.16 }, { "item_id":130, "item_category_id":10, "cost":114.39 }, { "item_id":66, "item_category_id":6, "cost":90.03 }, { "item_id":192, "item_category_id":12, "cost":74.78 }, { "item_id":27, "item_category_id":12, "cost":131.27 }, { "item_id":182, "item_category_id":2, "cost":23.37 } ] }, { "building_id":18, "purchases":[ { "item_id":82, "item_category_id":7, "cost":127.05 }, { "item_id":143, "item_category_id":8, "cost":106.03 }, { "item_id":86, "item_category_id":11, "cost":89.86 } ] }, { "building_id":18, "purchases":[ { "item_id":57, "item_category_id":12, "cost":112.88 }, { "item_id":10, "item_category_id":10, "cost":143.22 }, { "item_id":171, "item_category_id":6, "cost":46.61 }, { "item_id":136, "item_category_id":1, "cost":74.89 }, { "item_id":115, "item_category_id":10, "cost":134.47 }, { "item_id":160, "item_category_id":10, "cost":109.55 }, { "item_id":70, "item_category_id":10, "cost":19.32 }, { "item_id":26, "item_category_id":11, "cost":28.86 }, { "item_id":8, "item_category_id":8, "cost":110.61 }, { "item_id":43, "item_category_id":13, "cost":115.86 } ] }, { "building_id":17, "purchases":[ { "item_id":102, "item_category_id":12, "cost":117.67 }, { "item_id":136, "item_category_id":1, "cost":74.89 }, { "item_id":167, "item_category_id":2, "cost":65.36 }, { "item_id":173, "item_category_id":8, "cost":143.73 }, { "item_id":125, "item_category_id":5, "cost":113.33 }, { "item_id":140, "item_category_id":5, "cost":30.33 } ] }, { "building_id":16, "purchases":[ { "item_id":149, "item_category_id":14, "cost":106.59 }, { "item_id":152, "item_category_id":2, "cost":123.09 }, { "item_id":87, "item_category_id":12, "cost":1.46 }, { "item_id":49, "item_category_id":4, "cost":50.82 }, { "item_id":86, "item_category_id":11, "cost":89.86 }, { "item_id":48, "item_category_id":3, "cost":103.54 }, { "item_id":10, "item_category_id":10, "cost":143.22 }, { "item_id":162, "item_category_id":12, "cost":21.48 }, { "item_id":11, "item_category_id":11, "cost":70.23 }, { "item_id":118, "item_category_id":13, "cost":19.45 } ] }, { "building_id":16, "purchases":[ { "item_id":20, "item_category_id":5, "cost":133.59 }, { "item_id":82, "item_category_id":7, "cost":127.05 }, { "item_id":111, "item_category_id":6, "cost":60.91 } ] }, { "building_id":17, "purchases":[ { "item_id":22, "item_category_id":7, "cost":56.14 }, { "item_id":91, "item_category_id":1, "cost":22.52 }, { "item_id":149, "item_category_id":14, "cost":106.59 } ] }, { "building_id":18, "purchases":[ { "item_id":168, "item_category_id":3, "cost":54.33 }, { "item_id":22, "item_category_id":7, "cost":56.14 } ] }, { "building_id":17, "purchases":[ { "item_id":79, "item_category_id":4, "cost":53.53 }, { "item_id":60, "item_category_id":0, "cost":117.82 }, { "item_id":72, "item_category_id":12, "cost":148.69 }, { "item_id":107, "item_category_id":2, "cost":48.71 }, { "item_id":18, "item_category_id":3, "cost":142.67 }, { "item_id":145, "item_category_id":10, "cost":127.1 }, { "item_id":139, "item_category_id":4, "cost":132.47 } ] } ] } } ] need to figure out for example : total cost in the country( US) and which building ( name or id) has most total cost.
First thing I'd do is beautify that ugly JSON to a more human-friendly form, obtaining something like this: [ { "placeid": 1, "place_name": "arora-square", "city": "miami", "state": "florida", "country": "US" }, { "placeid": 2, "place_name": "hoover", "city": "palo-alto", "state": "california", "country": "US" } ] Once you're done with that, just remember that {} surrounds an object, while [] represents a list. In the first case, to access a specific property just use object.property, while in the second one you can access the i-th element using list[index]. For example, if you have o = {'key1': 'value1', 'key2': 'value2'}, you can easily retrieve value1 using v1 = o.key1.
Without using JSON.parse(), your JSON is basically an object and can be directly accessed from the array using the foreach method var response2 = [{"placeid":1,"place_name":"arora-square","city":"miami","state":"florida","country":"US"}, {"placeid":2,"place_name":"hoover","city":"palo-alto","state":"california","country":"US"}] response2.forEach(function(element) { console.log(element.placeid); console.log(element.place_name); console.log(element.city); console.log(element.state); console.log("---"); }); To use JSON.parse(), you need to convent your JSON into a string and then assign it to the array. After that, use foreach method to simply loop through the array content and parse each JSON content. var response1 = ["{\"placeid\":\"1\",\"place_name\":\"arora-square\",\"city\":\"miami\",\"state\":\"florida\",\"country\":\"US\"}", "{\"placeid\": \"2\",\"place_name\":\"hoover\",\"city\":\"palo-alto\",\"state\":\"california\",\"country\":\"US\"}"]; response1.forEach(function(element) { element = JSON.parse(element); console.log(element.placeid); console.log(element.place_name); console.log(element.city); console.log(element.state); console.log("---"); }); The second method will be applicable in cases like AJAX calls, where you are receiving back JSON encoded data.
Set selected on nested object knockout js
I have a complex object and I'm trying to set the SelectedTransportation property which I manually add in a mapping. The code properly populates the dropdownlist, but I can't figure out how to set SelectedTransportation properly. I've tried setting it during the mapping process and after mapping through a loop but all attempts have failed. Seems like this should be rather easy, but the solution eludes me. var model = {"LoadCarriers":[ { "Id":1, "IsDispatched":false, "IsPrimary":false, "RCNotes":null, "CarrierId":4, "Carrier":{ "Id":4, "Name":"West Chase", "MCNumber":"EPZEPFEEGJAJ", "DOTNumber":"AJSCEXFTFJ", "InternetTruckStopCACCI":"DJOGRBQ", "Phone":"0773283820", "RemitToPhone":null, "AlternatePhone":"4428290470", "Fax":null, "MainAddress":{ "ShortAddress":"Toledo, IN", "Address1":"Lee St", "Address2":"apt 131", "City":"Toledo", "State":"IN", "PostalCode":"07950", "Country":"US" }, "RemitToAddress":{ "ShortAddress":"Fuquay Varina, MO", "Address1":"Manchester Rd", "Address2":"", "City":"Fuquay Varina", "State":"MO", "PostalCode":"23343", "Country":"US" }, "EmailAddress":"jason.price14#gmail.com", "Coverage":null, "CanLoad":false, "InsuranceNumber":"RIQERAIAJBMP", "InsuranceExpirationDate":"\/Date(1442978115587)\/", "AdditionalInsurance":null, "ProNumber":"07643", "URL":"http://www.west-chase.com", "AccountId":1 }, "Dispatcher":"Bob McGill", "DriverId":null, "LoadDriver":{ "Id":1, "Name":"Bobby Pittman", "Phone":"8950121068", "Mobile":null, "MT":false, "Tractor":"OQRNBP", "Trailer":"QTZP", "Location":"Lee St", "TansportationSize":"958424896573544192", "Pallets":null, "IsDispatched":false, "TransportationId":7, "Transportation":{ "Name":"Flatbed or Van", "Id":7 }, "TransportationList":[ { "Name":"Flat", "Id":1 }, { "Name":"Van or Reefer", "Id":2 }, { "Name":"Rail", "Id":3 }, { "Name":"Auto", "Id":4 }, { "Name":"Double Drop", "Id":5 }, { "Name":"Flat with Tarps,", "Id":6 }, { "Name":"Flatbed or Van", "Id":7 }, { "Name":"Flatbed, Van or Reefer", "Id":8 }, { "Name":"Flatbed with Sides", "Id":9 }, { "Name":"Hopper Bottom", "Id":10 }, { "Name":"Hot Shot", "Id":11 }, { "Name":"Lowboy", "Id":12 }, { "Name":"Maxi", "Id":13 }, { "Name":"Power Only", "Id":14 }, { "Name":"Reefer w/ Pallet Exchange", "Id":15 }, { "Name":"Removable Gooseneck", "Id":16 }, { "Name":"Step Deck", "Id":17 }, { "Name":"Tanker", "Id":18 }, { "Name":"Curtain Van", "Id":19 }, { "Name":"Flatbed Hazardous", "Id":20 }, { "Name":"Reefer Hazardous", "Id":21 }, { "Name":"Van Hazardous", "Id":22 }, { "Name":"Vented Van", "Id":23 }, { "Name":"Van w/ Pallet Exchange", "Id":24 }, { "Name":"B-Train", "Id":25 }, { "Name":"Container", "Id":26 }, { "Name":"Double Flat", "Id":27 }, { "Name":"Flatbed or Stepdeck", "Id":28 }, { "Name":"Air", "Id":29 }, { "Name":"Ocean", "Id":30 }, { "Name":"Walking Floor", "Id":31 }, { "Name":"Landoll Flatbed", "Id":32 }, { "Name":"Conestoga", "Id":33 }, { "Name":"Load Out", "Id":34 }, { "Name":"Van Air-Ride", "Id":35 }, { "Name":"Container Hazardous", "Id":36 } ], "CarrierId":0, "Carrier":null }, "Carriers":null, "LoadId":1 } ]}; var loadDriverModel = function (data) { ko.mapping.fromJS(data, {}, this); this.SelectedTransportation = ko.observable(); }; var loadDriverMapping = { 'LoadDriver': { key: function (data) { return data.Id; }, create: function (options) { return new loadDriverModel(options.data); } } }; var carrierModel = function (data) { ko.mapping.fromJS(data, loadDriverMapping, this); }; var carrierMapping = { 'LoadCarriers': { key: function (data) { return data.Id; }, create: function (options) { return new carrierModel(options.data); } } }; var model = ko.mapping.fromJS(model); ko.applyBindings(model); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.js"></script> <!-- ko foreach: LoadCarriers --> <select class="form-control" data-bind="options:LoadDriver.TransportationList, optionsText:'Name', value:$data.LoadDriver.SelectedTransportation"></select> <!-- /ko -->
#JasonlPrice I can't test right now, but I suggest you to not use this in loadDriverModel function. Try create a variable and return that variable. Something like this: var loadDriverModel = function (data) { var viewModel = ko.mapping.fromJS(data); viewModel.SelectedTransportation = ko.observable(); return viewModel; };
I ended up replacing this var loadDriverModel = function (data) { ko.mapping.fromJS(data, {}, this); this.SelectedTransportation = ko.observable();} with the following. var loadDriverModel = function (data) { var self = this; ko.mapping.fromJS(data, {}, this); this.SelectedTransportation = ko.computed(function () { return ko.utils.arrayFirst(self.TransportationList(), function (item) { return item.Id() === self.TransportationId() }); }, self); }; Now it works properly. Computed Observables were the solution.
Google Visualization style roles in object-literal DataTable
I am creating Google Visualizations (currently ColumnCharts) from AJAX data, by returning an object literal suitable for passing to the DataTable constructor according to these docs: https://developers.google.com/chart/interactive/docs/reference#dataparam Data is all working, but I can't work out how to get the style roles working. I thought the documentation was saying to create the below, but it doesn't set the colors; what am I doing wrong? { "cols":[ { "id":"x", "type":"number", "label":"Period" }, { "id":"quotes", "type":"number", "label":"Quotes" }, { "id":"quotes_style", "type":"number", "p":{ "role":"style" } }, { "id":"orders", "type":"number", "label":"Converted to Orders" }, { "id":"orders_style", "type":"number", "p":{ "role":"style" } } ], "rows":[ { "c":[ { "v":0, "f":"2/2015" }, { "v":4 }, { "p":{ "style":"color:#dddddd" } }, { "v":3 }, { "p":{ "style":"color:#00d67c" } } ], "p":null } ], "p":null }
Okay, fixed it; first of all in cols the type of the column should be string; then in the rows, the style columns should just have v set to the style string, not p. (Found this by calling google.visualization.arrayToDataTable() on a working array in the help documentation and calling .toJSON() on the result - very handy!) Final JSON: { "cols":[ { "id":"x", "type":"number", "label":"Period" }, { "id":"quotes", "type":"number", "label":"Quotes" }, { "id":"quotes_style", "type":"string", "p":{ "role":"style" } }, { "id":"orders", "type":"number", "label":"Converted to Orders" }, { "id":"orders_style", "type":"string", "p":{ "role":"style" } } ], "rows":[ { "c":[ { "v":0, "f":"2/2015" }, { "v":4 }, { "v":"color:#dddddd" }, { "v":3 }, { "v":"color:#00d67c" } ], "p":null } ], "p":null }