Parsing JSON data efficiently into front end list - javascript

I have been browsing for the past 2 days and can't seem to find an answer to this anywhere.
I am using PHP to parse all of my SQL data into a JSON format here is an example of the JSON:
[
{
"id": "1",
"name": "Jim",
"age": "39",
"address": "12 High Street, London",
"hasCar": "1",
"speaksForeignLanguage": "1",
"canWorkNights": "1",
"isStudent": "1"
},
{
"id": "2",
"name": "Fred",
"age": "29",
"address": "13 High Street, London",
"hasCar": "1",
"speaksForeignLanguage": "1",
"canWorkNights": "1",
"isStudent": "0"
},
{
"id": "3",
"name": "Bill",
"age": "19",
"address": "14 High Street, London",
"hasCar": "1",
"speaksForeignLanguage": "1",
"canWorkNights": "0",
"isStudent": "0"
},
{
"id": "4",
"name": "Tom",
"age": "39",
"address": "15 High Street, London",
"hasCar": "1",
"speaksForeignLanguage": "0",
"canWorkNights": "0",
"isStudent": "0"
},
{
"id": "5",
"name": "Cathy",
"age": "29",
"address": "16 High Street, London",
"hasCar": "1",
"speaksForeignLanguage": "0",
"canWorkNights": "0",
"isStudent": "1"
},
{
"id": "6",
"name": "Petra",
"age": "19",
"address": "17 High Street, London",
"hasCar": "1",
"speaksForeignLanguage": "0",
"canWorkNights": "1",
"isStudent": "0"
},
{
"id": "7",
"name": "Heide",
"age": "39",
"address": "18 High Street, London",
"hasCar": "1",
"speaksForeignLanguage": "1",
"canWorkNights": "0",
"isStudent": "0"
},
{
"id": "8",
"name": "William",
"age": "29",
"address": "19 High Street, London",
"hasCar": "1",
"speaksForeignLanguage": "1",
"canWorkNights": "0",
"isStudent": "1"
},
{
"id": "9",
"name": "Ted",
"age": "19",
"address": "20 High Street, London",
"hasCar": "0",
"speaksForeignLanguage": "0",
"canWorkNights": "0",
"isStudent": "1"
},
{
"id": "10",
"name": "Mike",
"age": "19",
"address": "21 High Street, London",
"hasCar": "1",
"speaksForeignLanguage": "0",
"canWorkNights": "0",
"isStudent": "1"
},
{
"id": "11",
"name": "Jo",
"age": "19",
"address": "22 High Street, London",
"hasCar": "0",
"speaksForeignLanguage": "1",
"canWorkNights": "0",
"isStudent": "1"
}
]
That is just an example and isn't the actual data I am using, my JSON data contains 8 image image links for each row and contains more string data.
I need to list up to 120 records on the front end, this list will have filtered search options.
When the client visits the search page I am guessing they will need to load all of the JSON data which would probably cause a slow user experience.
Is there anyway JSON data can be loaded on request so the client doesn't need to load all of that data at once? So for example maybe only request the data for 10 records per page so the whole JSON file isn't loaded?
Any advice would be great.

You can use local storage. Should be something like this:
// your json data
var json = {};
// you have store it as string
localStorage.setItem("data", JSON.stringify(json));
Then in the page you need it, just get it like this:
var data = localStorage.getItem("data");
// if the "data" key isn't set on the storage, it returns null
if (data != null)
{
// now deserialize the string to json
data = JSON.parse(data);
}
The local storage is available in all major browsers versions, as you can see here.

Related

How can a JSON call another JSON

I am developing a simple application with AngularJS and I want to get the value of the price dynamically so I want to make a JSON call to another JSON and I am not sure if is this possible !
This is my data.json:
[{
"name": "city A",
"elements": [{
"id": "c01",
"name": "name1",
"price": "15",
"qte": "10"
}, {
"id": "c02",
"name": "name2",
"price": "18",
"qte": "11"
}, {
"id": "c03",
"name": "name3",
"price": "11",
"qte": "14"
}],
"subsities": [{
"name": "sub A1",
"elements": [{
"id": "sub01",
"name": "nameSub1",
"price": "1",
"qte": "14"
}, {
"id": "sub02",
"name": "nameSub2",
"price": "8",
"qte": "13"
}, {
"id": "sub03",
"name": "nameSub3",
"price": "1",
"qte": "14"
}]
}, {
"name": "sub A2",
"elements": [{
"id": "ssub01",
"name": "nameSsub1",
"price": "1",
"qte": "7"
}, {
"id": "ssub02",
"name": "nameSsub2",
"price": "8",
"qte": "1"
}, {
"id": "ssub03",
"name": "nameSsub3",
"price": "4",
"qte": "19"
}]
}, {
"name": "sub A3",
"elements": [{
"id": "sssub01",
"name": "nameSssub1",
"price": "1",
"qte": "11"
}, {
"id": "sssub02",
"name": "nameSssub2",
"price": "2",
"qte": "15"
}, {
"id": "sssub03",
"name": "nameSssub3",
"price": "1",
"qte": "15"
}]
}]
}, {
"name": "city B",
"elements": [{
"id": "cc01",
"name": "name11",
"price": "10",
"qte": "11"
}, {
"id": "cc02",
"name": "name22",
"price": "14",
"qte": "19"
}, {
"id": "cc03",
"name": "name33",
"price": "11",
"qte": "18"
}]
}, {
"name": "city C",
"elements": [{
"id": "ccc01",
"name": "name111",
"price": "19",
"qte": "12"
}, {
"id": "ccc02",
"name": "name222",
"price": "18",
"qte": "17"
}, {
"id": "ccc03",
"name": "name333",
"price": "10",
"qte": "5"
}]
}]
And I want to get the value of price from this url : url json
I want to do something like :
[{
"name": "city A",
"elements": [{
"id": "c01",
"name": "name1",
"price": "prix_diesel",/*prix_diesel is an attribute in json url I want to extract its value here.*/
"qte": "10"
}, {
"id": "c02",
"name": "name2",
"price": "18",
"qte": "11"
}, {
"id": "c03",
"name": "name3",
"price": "11",
"qte": "14"
}],
"subsities": [{
"name": "sub A1",
"elements": [{
"id": "sub01",
"name": "nameSub1",
"price": "1",
"qte": "14"
}, {
"id": "sub02",
"name": "nameSub2",
"price": "8",
"qte": "13"
}, {
"id": "sub03",
"name": "nameSub3",
"price": "1",
"qte": "14"
}]
}, {
"name": "sub A2",
"elements": [{
"id": "ssub01",
"name": "nameSsub1",
"price": "1",
"qte": "7"
}, {
"id": "ssub02",
"name": "nameSsub2",
"price": "8",
"qte": "1"
}, {
"id": "ssub03",
"name": "nameSsub3",
"price": "4",
"qte": "19"
}]
}, {
"name": "sub A3",
"elements": [{
"id": "sssub01",
"name": "nameSssub1",
"price": "1",
"qte": "11"
}, {
"id": "sssub02",
"name": "nameSssub2",
"price": "2",
"qte": "15"
}, {
"id": "sssub03",
"name": "nameSssub3",
"price": "1",
"qte": "15"
}]
}]
}
......
......
]
I set this up in my plunkr : plunkr
I search and I found that if I want to get the data from the URL, I'll need an XMLHttpRequest (with Angular, I can use $http.get). But here I am using a JSON which call another JSON file so how can I resolve this problem ? do you have any idea please !
You can't. JSON is not a programming language but an open standard for data transfer.
What you can do however is reference an object from the second file in the first file. An example:
[{
"name": "city A",
"elements": [{
"id": "c01",
"name": "name1",
"price": "prix_diesel",
"qte": "10"
}]
// Simplified
}]
And the JSON from your URL:
{
"prix": {
"prix_diesel": "8.25",
"prix_essence": "10.14",
"prix_aditive": "8.80"
}
}
Now write a JS function which finds the reference in your first JSON file prix_diesel and look up the value of that key in the JSON from the url 8.25.
An example would be similar to this:
for (var element of myJson.elements) {
var reference = element.price; // prix_diesel
var referenceValue = jsonFromUrl.prix[reference]; // 8.25
}
This will find all the prices of your elements based on their reference (which is actually just the name of a key in your second JSON).
A side note, I noticed the JSON from your URL is supposed to be protected by login functionality. However, like you demonstrate in your own post, with the correct endpoints the data is easily accessible without needing to log in. If this is a product you own and you don't want this data to be publically available I'd suggest looking into a solution to prevent non-logged in users from requesting data. Have a look at passportjs.org.
i forked your plunker (changed your data.json too)
after loading second json you can get it like(code is something like "prix_diesel". it is in updated json)
function getPrice(code){
return priceData.prix[code];
}
updated

Error when I try to parse my json

I am using AngularJs doing a simple application And I want to set a variable up in a javascript file in orther to call a json file.
This is my data.js :
[{
var data = require('data_old.json');
var json = JSON.parse(data);
alert(json["date"]); //01/05/2016
alert(json.date); //01/05/2016
"name": "city A",
"elements": [{
"id": "c01",
"name": "name1",
"price": "15",
"qte": "10"
}, {
"id": "c02",
"name": "name2",
"price": "18",
"qte": "11"
}, {
"id": "c03",
"name": "name3",
"price": "11",
"qte": "14"
}],
"subsities": [{
"name": "sub A1",
"elements": [{
"id": "sub01",
"name": "nameSub1",
"price": "1",
"qte": "14"
}, {
"id": "sub02",
"name": "nameSub2",
"price": "8",
"qte": "13"
}, {
"id": "sub03",
"name": "nameSub3",
"price": "1",
"qte": "14"
}]
}, {
"name": "sub A2",
"elements": [{
"id": "ssub01",
"name": "nameSsub1",
"price": "1",
"qte": "7"
}, {
"id": "ssub02",
"name": "nameSsub2",
"price": "8",
"qte": "1"
}, {
"id": "ssub03",
"name": "nameSsub3",
"price": "4",
"qte": "19"
}]
}, {
"name": "sub A3",
"elements": [{
"id": "sssub01",
"name": "nameSssub1",
"price": "1",
"qte": "11"
}, {
"id": "sssub02",
"name": "nameSssub2",
"price": "2",
"qte": "15"
}, {
"id": "sssub03",
"name": "nameSssub3",
"price": "1",
"qte": "15"
}]
}]
}, {
"name": "city B",
"elements": [{
"id": "cc01",
"name": "name11",
"price": "10",
"qte": "11"
}, {
"id": "cc02",
"name": "name22",
"price": "14",
"qte": "19"
}, {
"id": "cc03",
"name": "name33",
"price": "11",
"qte": "18"
}]
}, {
"name": "city C",
"elements": [{
"id": "ccc01",
"name": "name111",
"price": "19",
"qte": "12"
}, {
"id": "ccc02",
"name": "name222",
"price": "18",
"qte": "17"
}, {
"id": "ccc03",
"name": "name333",
"price": "10",
"qte": "5"
}]
}]
And this is my data.json
[{
"date":"01/05/2016"
}]
I call my data here.
angular.module("myApp",['zingchart-angularjs'])
.controller('MainController', ['$scope', '$http', function($scope, $http) {
$scope.chartBase = {
"type": "line",
"plotarea": {
"adjust-layout": true /* For automatic margin adjustment. */
},
"scale-x": {
"label": {
"text": "Above is an example of a category scale" /* Add a scale title with a label object. */
},
"labels": ["name1", "name2", "name3"] /* Add your scale labels with a labels array. */
},
"series": [{
"values": [15, 18, 11] //here the prices of city selected
},{
"values": [10, 11, 14] //here the qte of city selected
}]
};
$scope.chartData = angular.copy($scope.chartBase);
$http.get('data.js')
.then(function(response) {
$scope.cities = response.data; // save the request data
$scope.selectedCity = $scope.cities[0]; // select the first one
$scope.changeCity(); // update chart
}, function(error) { console.log(error); });
$scope.changeCity = function() {
if($scope.selectedSubCity || $scope.selectedCity){ // if something has been selected
$scope.data = ($scope.selectedSubCity || $scope.selectedCity).elements; // update elements field
// initialize the array to be displayed in chart
var labels = [];
var price = {
"values": []
};
var qte = {
"values": []
};
// fill the arrays to be displayed from the selected city (sub city)
angular.forEach($scope.data, function(item, index) {
labels.push(item.name);
price.values.push(parseInt(item.price));
qte.values.push(parseInt(item.qte));
});
console.log($scope.chartData)
// put selected values to the field that is used to render the chart
$scope.chartData["scale-x"].labels = labels;
$scope.chartData.series = [ price, qte ];
}
}
}]);
When I run this, the browser tell that I have this error :
SyntaxError: Unexpected token v in JSON at position 5
at Object.parse (native)
You can't have those in your data.js file as they are not valid JSON
var data = require('data_old.json');
var json = JSON.parse(data);
alert(json["date"]); //01/05/2016
alert(json.date); //01/05/2016
The error is pointing to the first "v" of "var". You can test your JSON here http://json.parser.online.fr/ on some other online validator.
Your file should look like this:
[{
"name": "city A",
"elements": [{
"id": "c01",
"name": "name1",
"price": "15",
"qte": "10"
}, {
"id": "c02",
"name": "name2",
"price": "18",
"qte": "11"
}, {
"id": "c03",
"name": "name3",
"price": "11",
"qte": "14"
}],
"subsities": [{
"name": "sub A1",
"elements": [{
"id": "sub01",
"name": "nameSub1",
"price": "1",
"qte": "14"
}, {
"id": "sub02",
"name": "nameSub2",
"price": "8",
"qte": "13"
}, {
"id": "sub03",
"name": "nameSub3",
"price": "1",
"qte": "14"
}]
}, {
"name": "sub A2",
"elements": [{
"id": "ssub01",
"name": "nameSsub1",
"price": "1",
"qte": "7"
}, {
"id": "ssub02",
"name": "nameSsub2",
"price": "8",
"qte": "1"
}, {
"id": "ssub03",
"name": "nameSsub3",
"price": "4",
"qte": "19"
}]
}, {
"name": "sub A3",
"elements": [{
"id": "sssub01",
"name": "nameSssub1",
"price": "1",
"qte": "11"
}, {
"id": "sssub02",
"name": "nameSssub2",
"price": "2",
"qte": "15"
}, {
"id": "sssub03",
"name": "nameSssub3",
"price": "1",
"qte": "15"
}]
}]
}, {
"name": "city B",
"elements": [{
"id": "cc01",
"name": "name11",
"price": "10",
"qte": "11"
}, {
"id": "cc02",
"name": "name22",
"price": "14",
"qte": "19"
}, {
"id": "cc03",
"name": "name33",
"price": "11",
"qte": "18"
}]
}, {
"name": "city C",
"elements": [{
"id": "ccc01",
"name": "name111",
"price": "19",
"qte": "12"
}, {
"id": "ccc02",
"name": "name222",
"price": "18",
"qte": "17"
}, {
"id": "ccc03",
"name": "name333",
"price": "10",
"qte": "5"
}]
}]
var data = require('data_old.json');
var json = JSON.parse(data);
alert(json["date"]); //01/05/2016
alert(json.date); //01/05/2016
Why do you add those at the beginning of the JSON ? They cannot be parsed by your script, thus displaying the Syntax Error. What do you want to do exactly ?

How to add anther "entry" into this JSON?

I downloaded some JSON, as shown below. In the developer console it looks like an object containing nested objects which contain nested objects ...
I would like to add a new, empty "campaign" into the data (at the front). How do I do that?
Insert
var blankCampaignData = {'title': '', 'description': '', 'path_to_logo': '', 'start_time': date, 'end_time' : date, 'paused': false};
into
{
"campaigns": {
"1": {
"campaign_id": "1",
"title": "Nike Air 2015 campaign",
"description": null,
"path_to_logo": null,
"start_time": "09/11/2015 22:42:08",
"end_time": "09/03/2016 22:42:08",
"paused": "0",
"destinations": {
"1": {
"destination_id": "1",
"campaign_id": "1",
"url": "www.nike.com/nike_air",
"description": "Nike air destination",
"connections": {
"3": {
"connection_id": "3",
"destination_id": "1",
"tag_id": "0",
"country": "Scotland",
"county": "Yorkshire",
"town": "East Ham",
"post_code": "SE1 1AA",
"custom": "bus stop",
"description": "Connection number 3"
}
}
},
"2": {
"destination_id": "2",
"campaign_id": "1",
"url": "www.nike.com/nike_air/sub_campaign",
"description": "Nike air - free laces promotion destination",
"connections": {
"2": {
"connection_id": "2",
"destination_id": "2",
"tag_id": "0",
"country": "Engerland",
"county": "Devon",
"town": "East Ham",
"post_code": "SE1 1AA",
"custom": "bus stop",
"description": "Connection number 2"
},
"4": {
"connection_id": "4",
"destination_id": "2",
"tag_id": "0",
"country": "Engerland",
"county": "Yorkshire",
"town": "Felixswtowe",
"post_code": "RB3 9YR",
"custom": "police staticon",
"description": "Connection number 4"
},
"6": {
"connection_id": "6",
"destination_id": "2",
"tag_id": "0",
"country": "Scotland",
"county": "Essex",
"town": "York",
"post_code": "JD8 4LF",
"custom": "somewhere else",
"description": "Connection number 6"
},
"9": {
"connection_id": "9",
"destination_id": "2",
"tag_id": "0",
"country": "Scotland",
"county": "Cork",
"town": "York",
"post_code": "JD8 4LF",
"custom": "in the ladies' loo",
"description": "Connection number 9"
}
}
}
}
},
"2": {
"campaign_id": "2",
"title": "Nike football boots campaign",
"description": null,
"path_to_logo": null,
"start_time": "09/12/2015 22:42:08",
"end_time": "09/01/2016 22:42:08",
"paused": "0",
"destinations": {
"3": {
"destination_id": "3",
"campaign_id": "2",
"url": "www.nike.com/nike_football_boots/",
"description": "Nike footie boots destination",
"connections": {}
},
"4": {
"destination_id": "4",
"campaign_id": "2",
"url": "www.nike.com/nike_football_boots/sub_campaign",
"description": "Buy left boot, get right boot free destination",
"connections": {}
}
}
},
"3": {
"campaign_id": "3",
"title": "Nike general promotion campaign",
"description": null,
"path_to_logo": null,
"start_time": "09/12/2013 22:42:08",
"end_time": "09/08/2016 22:42:08",
"paused": "0",
"destinations": {
"5": {
"destination_id": "5",
"campaign_id": "3",
"url": "www.nike.com/general_promotion",
"description": "Nike general promotion destination",
"connections": {}
},
"6": {
"destination_id": "6",
"campaign_id": "3",
"url": "www.nike.com/general_promotion/discount_coupon",
"description": "20% off coupon destination",
"connections": {}
}
}
}
}
}
Work out what the next campaign id should be:
var nextId = +Object.keys(obj.campaigns).sort().pop() + 1;
Add the empty campaign to the campaigns object. Obviously you'll need to define date beforehand.
obj.campaigns[nextId] = {
'title': '',
'description': '',
'path_to_logo': '',
'start_time': date,
'end_time' : date,
'paused': false
}

Group by JSON array using jQuery

I have a set of JSON array and I want the result to be grouped by the "Id" column. I will not use underscore.js for this, as this can't be used in our project. The only option is to do it with jQuery. My source array and expected results are below.
var origObj = [{ "Id": "1", "name": "xxx", "age": "22" },
{ "Id": "1", "name": "yyy", "age": "15" },
{ "Id": "5", "name": "zzz", "age": "59" }]
var output = [{"1": [{ "Id": "1", "name": "xxx", "age": "22" },
{ "Id": "1", "name": "yyy", "age": "15" }],
"5": [{ "Id": "5", "name": "zzz", "age": "59" }]}]
You can use Array.prototype.reduce to get this done. Check this post for more details https://stackoverflow.com/a/22962158/909535 Extending on that this is what you would need
var data= [{ "Id": "1", "name": "xxx", "age": "22" },
{ "Id": "1", "name": "yyy", "age": "15" },
{ "Id": "5", "name": "zzz", "age": "59" }];
console.log(data.reduce(function(result, current) {
result[current.Id] = result[current.Id] || [];
result[current.Id].push(current);
return result;
}, {}));
Try
var origObj = [{ "Id": "1", "name": "xxx", "age": "22" },
{ "Id": "1", "name": "yyy", "age": "15" },
{ "Id": "5", "name": "zzz", "age": "59" }], output;
output = [origObj.reduce((a,c) => (a[c.Id]=(a[c.Id]||[]).concat(c),a) ,{})];
console.log(output);

accessing Javascript object

may be a simple issue but cannot seem to solve it after some searching as well :) .. The scenario is as follows:
Using PhoneGap, am receiving a json object via Ajax using jquery. the object needs to be displayed on a next screen (first is the Search page and the next is the Search result page).
when the object is received, it is being saved in the sessionStorage variable (e.g. sessionStorage.result = data).
but when it is tried to be accessed on the next page, it gives an error saying that the property is unknown. e.g.
var result = sessionStorage.result;
alert(result.response.businesses[0].name);
have also tried:
alert($(result.response.businesses[0].name));
it says that the property is unknow. the basic structure of the json is as follows:
{
"action": "SearchBusiness",
"meta": {
"code": 200,
"message": "OK"
},
"response": {
"searchQuery": {
"categoryId": 4,
"communityId": 4,
"latitude": "",
"longitude": "",
"category": "Grocery Stores",
"community": "Indian/Pakistani",
"searchRadius": "",
"city": "",
"postalCode": ""
},
"businesses": [
{
"businessId": "2",
"name": "Name",
"address": "123",
"phone": "(123) 456 7890",
"city": "any city",
"country": "United States",
"state": "Abc",
"postalCode": "a123",
"url": "",
"logoUrl": null,
"latitude": "0.1951704",
"longitude": "-1.89512",
"categoryId": "4",
"communityId": "4",
"ratings": "0",
"ratingAvg": "0.00",
"distance": 0
}
]
Any help appreciated.
You are wrongly accessing that value,
Try,
var result = JSON.parse(sessionStorage.result);
alert($(result.businesses[0].name));
in your json codes missing } your codes must be like that
{
"action": "SearchBusiness",
"meta": {
"code": 200,
"message": "OK"
},
"response": {
"searchQuery": {
"categoryId": 4,
"communityId": 4,
"latitude": "",
"longitude": "",
"category": "Grocery Stores",
"community": "Indian/Pakistani",
"searchRadius": "",
"city": "",
"postalCode": ""
},
"businesses": [{
"businessId": "2",
"name": "Name",
"address": "123",
"phone": "(123) 456 7890",
"city": "any city",
"country": "United States",
"state": "Abc",
"postalCode": "a123",
"url": "",
"logoUrl": null,
"latitude": "0.1951704",
"longitude": "-1.89512",
"categoryId": "4",
"communityId": "4",
"ratings": "0",
"ratingAvg": "0.00",
"distance": 0
}]
}
}
alert(result.response.businesses[0].name); // it will work i think. no error
also look sessionstroge is there any data
Your Json string is not a valid JSON format plz check the format
{
"action": "SearchBusiness",
"meta": {
"code": 200,
"message": "OK"
},
"response": {
"searchQuery": {
"categoryId": 4,
"communityId": 4,
"latitude": "",
"longitude": "",
"category": "Grocery Stores",
"community": "Indian/Pakistani",
"searchRadius": "",
"city": "",
"postalCode": ""
},
"businesses": [{
"businessId": "2",
"name": "Name",
"address": "123",
"phone": "(123) 456 7890",
"city": "any city",
"country": "United States",
"state": "Abc",
"postalCode": "a123",
"url": "",
"logoUrl": null,
"latitude": "0.1951704",
"longitude": "-1.89512",
"categoryId": "4",
"communityId": "4",
"ratings": "0",
"ratingAvg": "0.00",
"distance": 0
}]
}
}

Categories

Resources