How to parse json array of arrays in jQuery or AngularJS - javascript

Hi My Json Looks like below and i want to parse it to bind the data to array. Please provide me how i can parse it?
[
{
"ImgUrl": "http://www.cowboysalamocityharley.com/used_bikes/DSC_7815.JPG",
"CarouselImages": [
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7816.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7817.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7818.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7819.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7820.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7821.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7822.JPG"
],
"VehicleId": 1
},
{
"ImgUrl": "http://www.cowboysalamocityharley.com/used_bikes/DSC_7816.JPG",
"CarouselImages": [
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7816.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7817.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7818.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7819.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7820.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7821.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7822.JPG"
],
"VehicleId": 2
},
{
"ImgUrl": "http://www.cowboysalamocityharley.com/used_bikes/DSC_7817.JPG",
"CarouselImages": [
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7816.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7817.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7818.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7819.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7820.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7821.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7822.JPG"
],
"VehicleId": 3
},
{
"ImgUrl": "http://www.cowboysalamocityharley.com/used_bikes/DSC_7818.JPG",
"CarouselImages": [
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7816.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7817.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7818.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7819.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7820.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7821.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7822.JPG"
],
"VehicleId": 4
}
]
is there any way i can parse it using an inbuilt library or shall i need to loop through?

try this
var json = eval("(" + result + ")");

Try this:
var arr = JSON.parse(data);

Related

jquery returning json data as undefined and images are not loading

I am trying to gain access within the last array of the json file and return the value from the "data" array of the json file and put it into the choiceSelection array. However, on my local host, it returns an undefined value and the images would not load. Can anyone help me out? I apologise if I haven't clearly explained my problem/logic and so please ask me for more details, if you're not sure. Thanks!
javascript code
$.getJSON('data.json', function(json) {
if(json[2].data){
for (i = 0; i < json[3].data.length; i++) {
choiceSelection[i] = new Array;
choiceSelection[i][0] = json[2].data[i].question;
choiceSelection[i][1] = json[2].data[i].correctChoice;
choiceSelection[i][2] = json[2].data[i].choice1;
choiceSelection[i][3] = json[2].data[i].choice2;
}
// choiceSelection.length = choiceSelection.length;
displayQuestion();
console.log(json[2]);
}
})
json file
[
{
"name": "match numbers 1",
"template": "matching",
"data": [
[
"six",
"Images/Number6.jpg"
],
[
"eight",
"Images/Number8.jpg"
],
[
"nine",
"Images/Number9.jpg"
]
]
},
{
"name": "order numbers 1",
"template": "ordering",
"data": [
[
"Images/Number6.jpg"
],
[
"Images/Number8.jpg"
],
[
"Images/Number9.jpg"
]
]
},
{
"name": "animal",
"template": "picture game",
"data": [
{
"question": "Where is the cat?",
"correctChoice": "Images/5cats.jpg",
"choice1": "Images/squirrel.png",
"choice2": "Images/beagle.png"
},
{
"question": "Where is the cat?",
"correctChoice": "Images/5cats.jpg",
"choice1": "Images/squirrel.png",
"choice2": "Images/beagle.png"
}
]
}
]
Edit 1: change json[i] to json[2].data. Still undefined
Edit 2: changed json[2].data. to json[2].data[i] and used json[3].data.length in the for statement. It works perfectly now. Thank you everyone for the help!:)
You could take the hassle out of your code and use some ES6 destructuring to get at your data more easily.
const json = '[{"name":"match numbers 1","template":"matching","data":[["six","Images/Number6.jpg"],["eight","Images/Number8.jpg"],["nine","Images/Number9.jpg"]]},{"name":"order numbers 1","template":"ordering","data":[["Images/Number6.jpg"],["Images/Number8.jpg"],["Images/Number9.jpg"]]},{"name":"animal","template":"picture game","data":[{"question":"Where is the cat?","correctChoice":"Images/5cats.jpg","choice1":"Images/squirrel.png","choice2":"Images/beagle.png"},{"question":"Where is the cat?","correctChoice":"Images/5cats.jpg","choice1":"Images/squirrel.png","choice2":"Images/beagle.png"}]}]'
function getJSON(endpoint, callback) {
setTimeout(() => callback(JSON.parse(json)), 1000);
}
// grab the third object from the response data
getJSON('data.json', function([ ,,obj ]) {
// grab the data array from that object but relabel it
// `choiceSelection
const { data: choiceSelection } = obj;
// then use the object property keys to get access
// to the data instead of indexes. Much easier.
console.log(choiceSelection[0].question);
console.log(choiceSelection[1].question);
});

Javascript/json keep in database and special chars

I have layout builder in React to keep data structure and text I use ImmutableJS objects.
Such structure with attributes as text or css styles is saved into database as JSON.
To make it JSON I using json-immutable library: serialize, deserialize functions.
After save in database I provide configuration for react components as javascript variables. For example my backend generate js file with variables or small part is printing directly in html code using script tag.
Data are JSON or decoded javascript.
The biggest problem I have with save special chars.
For example if someone set ' single quote in some attribute it is saved directly.
But when I print it in html code as
var myConfig = '{anyjson}';
when inside JSON is single quote parser throw error. The same with double quotes, & (ampersant) or any chars used in html code like <,/>
Single quote I replace to \' when I print it in html code.
But I think does exists any way to save keep all data in JSON and still they will easy to decode by deserialize function to parse JSON to ImmutableJS objects.
Code example
https://jsfiddle.net/jaroapp/2yzud6ua/2/
var structure = {
"__iterable":"Map",
"data":[
[
"entityMap",
{
"__iterable":"Map",
"data":[
[
"html_el_qb7tyhi",
{
"__iterable":"Map",
"data":[
[
"imported",
false
],
[
"path",
"html_el_qb7tyhi"
],
[
"componentData",
{
"__iterable":"Map",
"data":[
]
}
],
[
"draftjsObject",
{
"__iterable":"OrderedMap",
"data":[
]
}
],
[
"draftjs",
true
],
[
"data",
{
"__iterable":"OrderedMap",
"data":[
[
"text",
"B&B is the best company. It's my hope for new markets."
]
]
}
],
[
"chunk",
null
],
[
"style",
{
"__iterable":"OrderedMap",
"data":[
[
"background-image",
"url(\"/path/to/image.jpg\")"
]
]
}
],
[
"attr",
{
"__iterable":"OrderedMap",
"data":[
]
}
],
[
"runEditor",
false
],
[
"entityMap",
{
"__iterable":"OrderedMap",
"data":[
]
}
],
[
"type",
"div"
],
[
"key",
"html_el_qb7tyhi"
]
]
}
],
[
"html_el_2dgupn7",
{
"__iterable":"Map",
"data":[
[
"imported",
false
],
[
"path",
"html_el_2dgupn7"
],
[
"componentData",
{
"__iterable":"Map",
"data":[
]
}
],
[
"draftjsObject",
{
"entityMap":{
},
"blocks":[
{
"key":"3ia22",
"text":"Text saved with html inside",
"type":"unstyled",
"depth":0,
"inlineStyleRanges":[
],
"entityRanges":[
],
"data":{
}
}
]
}
],
[
"draftjs",
true
],
[
"data",
{
"__iterable":"OrderedMap",
"data":[
[
"text",
null
],
[
"html",
"<p class=\"md-block-unstyled\">Text saved with html inside</p>"
]
]
}
],
[
"chunk",
null
],
[
"style",
{
"__iterable":"OrderedMap",
"data":[
]
}
],
[
"attr",
{
"__iterable":"OrderedMap",
"data":[
]
}
],
[
"runEditor",
false
],
[
"entityMap",
{
"__iterable":"OrderedMap",
"data":[
]
}
],
[
"type",
"div"
],
[
"key",
"html_el_2dgupn7"
]
]
}
]
]
}
],
[
"containersMap",
{
"__iterable":"Map",
"data":[
]
}
],
[
"componentsMap",
{
"__iterable":"Map",
"data":[
[
"entityMap",
{
"__iterable":"OrderedMap",
"data":[
]
}
]
]
}
]
]
};
Such structure I set as parameter into ReactJS component.
If I set it as JSON and wrap in quotes then the browser throws an error. If I set it as JavaScript object into the React component I can't make ImmutableJS from this one, because this structure is read by this
https://www.npmjs.com/package/json-immutable library (I use the same to make JSON from Immutable JS to save it in database);
Thanks in advance for any hints.
I solved this problem. Short description, maybe will helpful for someone.
I get file with deserialize function form json-immutable package. And I modified function deserialize to
export function deserialize(json){
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if(typeof json==='string'){
return JSON.parse(json, function(key, value, options){
return revive(key, value, options);
});
}else{
return JSON.parse(JSON.stringify(json), function(key, value, options){
return revive(key, value, options);
});
}
}
Function in package use JSON.parse for param. Maybe it's not the most elegant solution but I don't have time to find way to don't "re-json" object. Standard Object.keys and map return origin object.

Apply regex expression to a json response data

Scenario client make a GET request the response is in a JSON format like this one
var data = {
"enabled": true,
"state": "schedule",
"schedules": [
{
"rule": {
"start": "2014-06-29T12:36:26.000",
"end": "2014-06-29T12:36:56.000",
"recurrence": [
"RRULE:FREQ=MINUTELY"
]
},
"wifi_state_during_rule": "disabled",
"end_state": "enabled"
}
],
"calculated_wifi_state_now": "disabled",
"time_of_next_state_change": [
"2014-07-08T18:56:56.000Z",
"2014-07-08T18:57:56.000Z"
]
};
For the purpose of this example I stored the result in a variable called "data".
My regex Expressions is:
checkPattern = /"\w+\"(?=:)/ //all keys "keyname": ...
The basic ideia here its just to get the keynames besides being inside of and object or array...since the definition of keyname's in JSON is "keyname": that's why I'm trying to use the above regex expression.
I even thought about doing this with a recursive function but is not working.
You never should parse non-regular structures with regular expressions.
Just collect what you want from parsed json object.
Just run data = JSON.parse(json_string) for parse it
function getKeysRecursive(obj) {
var result = [];
for (var key in obj) {
result.push(key);
if (typeof obj[key] == 'object') {
result = result.concat(getKeysRecursive(obj[key]));
}
}
return result;
}
getKeysRecursive(({
"enabled": true,
"state": "schedule",
"schedules": [
{
"rule": {
"start": "2014-06-29T12:36:26.000",
"end": "2014-06-29T12:36:56.000",
"recurrence": [
"RRULE:FREQ=MINUTELY"
]
},
"wifi_state_during_rule": "disabled",
"end_state": "enabled"
}
],
"calculated_wifi_state_now": "disabled",
"time_of_next_state_change": [
"2014-07-08T18:56:56.000Z",
"2014-07-08T18:57:56.000Z"
]
}))
// ["enabled", "state", "schedules", "0", "rule", "start", "end", "recurrence", "0", "wifi_state_during_rule", "end_state", "calculated_wifi_state_now", "time_of_next_state_change", "0", "1"]
You can filter them, sort, exclude numeric keys... All what you need.
You wont need a regular expression for this . Javascript has a built in function to extract Object key names .
Example :
Use Object.keys();
var data = {
"enabled": true,
"state": "schedule",
"schedules": [
{
"rule": {
"start": "2014-06-29T12:36:26.000",
"end": "2014-06-29T12:36:56.000",
"recurrence": [
"RRULE:FREQ=MINUTELY"
]
},
"wifi_state_during_rule": "disabled",
"end_state": "enabled"
}
],
"calculated_wifi_state_now": "disabled",
"time_of_next_state_change": [
"2014-07-08T18:56:56.000Z",
"2014-07-08T18:57:56.000Z"
]
};
Then
console.log(Object.keys(data));
should print
["enabled","state","schedules","calculated_wifi_state_now","time_of_next_state_change"]
Proof: http://codepen.io/theConstructor/pen/zBpWak
Now all of your object keys are stored in an array ..
Hope this helps
This will give you all of the keys as the matches:
\"(\w+)(?:\"\:)
https://regex101.com/r/iM9wB3/2
Edited to work with multiple keys on one line.

Converting JSON/JS Object to array

I have a JSON response from my API that is structured like so:
{
"data": [
{
"id": "1", "name": "test"
},
{
"id": "2", "name": "test2"
}
]
}
When I reference data I get the array with each record. I need the curly braces to be brackets due to a plugin I am using requiring it to be an array.
Desired output:
[
["1", "test"],
["2", "test"]
]
How can I convert the above JSON to this?
Edit:
This turned out to be a problem with a plugin I was using, and I knew how to do this fine all along. Thought I was going crazy but my code was fine, some plugin was screwing things up.
You can do this using Array.prototype.map
var arr = json.data.map(function(x){
return [x.id, x.name];
});
Something like this maybe: http://jsfiddle.net/3gcg6Lbz/1/
var arr = new Array();
var obj = {
"data": [
{
"id": "1", "name": "test"
},
{
"id": "2", "name": "test2"
}
]
}
for(var i in obj.data) {
var thisArr = new Array();
thisArr.push(obj.data[i].id);
thisArr.push(obj.data[i].name);
arr.push(thisArr);
}
console.log(arr);

JSON/JS Object accessing key when you don't know the name in Google Apps Script

I'm working with a response from the Webtrends API in Google apps script and I have a JSON/JS object that looks like this:
"data": [
{
"period": "Month",
"start_date": "2013-12",
"end_date": "2013-12",
"attributes": {},
"measures": {
"Visits": 500
},
"SubRows": [
{
"facebook.com": {
"attributes": {},
"measures": {
"Visits": 100
},
"SubRows": null
},
"google.co.uk": {
"attributes": {},
"measures": {
"Visits": 100
},
"SubRows": null
},
"newsnow.co.uk": {
"attributes": {},
"measures": {
"Visits": 100
},
"SubRows": null
},
"No Referrer": {
"attributes": {},
"measures": {
"Visits": 100
},
"SubRows": null
},
"t.co": {
"attributes": {},
"measures": {
"Visits": 100
},
"SubRows": null
}
}
]
}
]
What I need to access is the names i.e facebook.com etc... and visit numbers for each of the SubRows.
I'm able to get the visit numbers, but I can't work out how to get the names. Please note the names will change constantly as different sites will send different amounts of traffic each day.
Section of my code at the moment where I get the visit numbers:
for(i in dObj){
var data = dObj[i].SubRows;
var sd = dObj[i].start_date;
var ed = dObj[i].end_date;
if(sd == ed){
var timep = ""+ sd;
}
else{
var timep = ""+ sd + "-" + ed;
}
var subRows = data[0];
Logger.log(subRows);
for(i in subRows){
var row = subRows[i];
var rmeasures = row.measures;
var rvis = rmeasures.Visits;
values = [timep,"",rvis]; //Blank string for where the name of the site would go
}
}
I've tried the following links, but none of them seem to have the answer:
Getting JavaScript object key list
How to access object using dynamic key?
How to access key itself using javascript
How do I access properties of a javascript object if I don't know the names?
I'm just using vanilla google apps script as I don't have any experience with Jquery etc...
Any help would be much appreciated!
I usually use a little helper function that looks like this:
var keyVal = function(o) {
var key = Object.keys(o)[0];
return {"key": key, "val":o[key]};
} ;
This will map an object with a variable key to a key/value object {key:...., val:{}}, which is usually convenient enough to work with.
describe.only ("stack overflow answer", function(){
it ("is should create a key/value pair" , function(){
var res = keyVal( {
"facebook.com": {
"attributes": {},
"measures": {
"Visits": 100
},
"SubRows": null
}});
res.key.should.equal('facebook.com');
res.val.attributes.should.deep.equal({});
});
Within the loop, the variable i contains the current key. Replacing the empty string with i should give you what you need.
You might also want to look at some of the more functional tools built into Javascript. Some more concise code might also be more explicit:
data.map(function(datum) {
var timep = datum.start_date == datum.end_date ? datum.end_date :
(data.start_date + "-" + datum.end_date);
return datum.SubRows.map(function(subRow) {
return Object.keys(subRow).map(function(key) {
return [timep, key, subRow[key].measures.Visits];
});
});
});
would return an object something like this:
[
[
[
["2013-12", "facebook.com", 100],
["2013-12", "google.co.uk", 100],
["2013-12", "newsnow.co.uk", 100],
["2013-12", "No Referrer", 100],
["2013-12", "t.co", 100 ]
]
]
]
This just uses map and Object.keys to simplify some of what you're doing with explicit loops.

Categories

Resources