assigning data to dynamic list variable in javascript - javascript

I have requirement where I need to create dynamic json data.
For which i will get two values, columnName and columnValue
var filterJsonColumns = [];
var genericFilter = function (columnName , columnValue) {
if (filterOn != "") {
$scope.filterJsonColumns[columnName ].push(columnValue);
}
console.log("$scope.filterJsonColumns", $scope.filterJsonColumns);
}
For this case I am using dynamic variable for the creation of JSON
ColumnName can have either status or stage or both.
So for in this case JSON should be like
JSON
filterJsonColumns={"status":["1","2"],"stage":["4","5"]}
This JSON formatting is not proper, but still I need this type of data.

Try This
var filterJsonColumns = {};
var genericFilter = function (columnName , columnValue) {
if (filterOn != "") {
if(!filterJsonColumns[columnName]){
filterJsonColumns[columnName] = [];
}
filterJsonColumns[columnName].push(columnValue);
}
console.log("filterJsonColumns",filterJsonColumns);

Related

Passing javascript object containing another array of objects to localStorage and then to java servlet using ajax

I am trying to work out how to store a javascript object in local storage that has a few items as well as an array of objects, if that is possible. To then extract the data from the local storage and send to a java servlet using ajax, then extract the data from the java HttpServletRequest. Here is some of the code I have written. It's a bit too complex to put the entire code base here. I have multiple forms which a user completes and as they move between forms I store the data entered into local storage.
const object = localStorage.getItem(scenarioName);
let scenarioObject = JSON.parse(object);
if (formIsValid) {
scenarioObject.SUPER_BALANCE = 420000;
scenarioObject.SUPER_INVESTMENT_FEES = 0.14;
scenarioObject.SUPER_ADMIN_FEES = 120;
scenarioObject.LIFE_INSURANCE = 200000;
scenarioObject.ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION = 1500;
let objectString = JSON.stringify(scenarioObject);
localStorage.setItem(scenarioName, objectString);
}
To extract the data from local storage I do the following:
const object = localStorage.getItem(activeScenario);
const jsonString = JSON.parse(object);
const yourSuperBalance = jsonString.SUPER_BALANCE;
$("#your-super-balance").val(yourSuperBalance);
const yourInvestmentFees = jsonString.SUPER_INVESTMENT_FEES;
$("#super-investment-fees").val(yourInvestmentFees);
const yourSuperAdminFees = jsonString.SUPER_ADMIN_FEES;
$("#super-admin-fees").val(yourSuperAdminFees);
const yourInsurance = jsonString.LIFE_INSURANCE;
$("#life-insurance").val(yourInsurance);
const yourAnnualSuperContribution = jsonString.ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION;
$("#your-annual-lump-sum-super-contribution").val(yourAnnualSuperContribution);
This all works fine, but now I wanted to add an array of objects from a table. I could not figure out a way to add this so I ended up storing two items in local storage. One for all the form data and one for the table data. I didn't like this approach but couldn't get it to work otherwise. Here is how I did the table:
function getSuperContributionsTableDataString(table) {
let yourSuperContributionsTableData = [];
let jsonData;
// commence for loop at 1 because the first row will be the header row and we want to skip that
for (let i = 1; i < table.rows.length; i++) {
let row = table.rows[i];
// first check all cells in row have a value, if not ignore
if (row.cells[0].innerText !== "" && row.cells[1].innerText !== "" && row.cells[2].innerText !== "") {
// As we are pushing the last element pushed becomes the first element in the array
// therefore, we push the before or after tax first and age last
jsonData = {};
jsonData[SUPER_TAXATION_CONTRIBUTION] = row.cells[2].innerText;
jsonData[SUPER_AMOUNT_CONTRIBUTION] = row.cells[1].innerText;
jsonData[SUPER_AGE_CONTRIBUTION] = row.cells[0].innerText;
yourSuperContributionsTableData.push(jsonData);
}
}
return JSON.stringify(yourSuperContributionsTableData);
}
let superContributionsTableDataString = getSuperContributionsTableDataString(
document.getElementById("your-extra-super-contributions-table"));
localStorage.setItem(scenarioName+ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION, superContributionsTableDataString);
This all worked but then I had to figure out how to send this data to the server using ajax. Without the table, everything was working fine as follows:
function sendScenarioDetailsToServer() {
let activeScenario = localStorage.getItem(ACTIVE_SCENARIO_KEY);
let item = localStorage.getItem(activeScenario);
let passedData = JSON.parse(item);
$.ajax({
type: "POST",
url: "ScenarioServlet",
data: passedData,
success: function (data) {
const SUCCESS_INT = data.length - 1;
if (data[SUCCESS_INT].SUCCESS === FAIL) {
displayPopupMessage("Error saving scenario ", "Save Scenario");
}else {
displayResult();
}
},
error: function (error, status) {
console.log(`Error ${error}`);
const stackTrace = getStackTrace();
const message = "An error occurred sending your data to the server for calculation. ";
displayPopupMessage(message, "Server Error.", stackTrace);
}
});
}
I modified this function as follows to add the table data and everything in the java servlet code went wrong.
function sendScenarioDetailsToServer() {
let activeScenario = localStorage.getItem(ACTIVE_SCENARIO_KEY);
let item = localStorage.getItem(activeScenario);
let passedData = JSON.parse(item);
// superannuation table
const superTable = activeScenario+ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION;
// this is already stringified
const superTableItem = localStorage.getItem(superTable);
const superTableData = '&' + ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION + "=" + superTableItem;
const formData = passedData + superTableData;
console.log("formData " + formData);
$.ajax({
type: "POST",
url: "ScenarioServlet",
data: passedData + superTableData,
success: function (data) {
const SUCCESS_INT = data.length - 1;
if (data[SUCCESS_INT].SUCCESS === FAIL) {
// TODO display messages
displayPopupMessage("Error saving scenario ", "Save Scenario");
}else {
displayResult();
}
},
error: function (error, status) {
console.log(`Error ${error}`);
const stackTrace = getStackTrace();
const message = "An error occurred sending your data to the server for calculation. ";
displayPopupMessage(message, "Server Error.", stackTrace);
}
});
}
Can anyone advise how best to store a javascript object in local storage that has an item inside the object which is an array of objects for a table? How do I store this in local storage, retrieve it from local storage, send it to the java servlet using ajax and then retrieve it from the HttpServletRequest. Any assistance would be much appreciated.
I worked out a way to do this. I shall fully explain the situation and then my solution to the problem. Not sure if this is the best solution but it does work.
The situation is that I have multiple forms where the user enters data for calculations, including a table of data. I wanted to store this data on local storage for later retrieval next time the user uses the website. The calculations are done in Java on the server so when the user clicks on something like "calculate" the data in local storage is then sent to the server to perform the calculations and the result is sent back.
I needed to store a javascript object containing some elements plus a table, so basically a javascript object with an array inside it.
Collect data from the table
function getSuperContributionsTableDataString(table) {
let yourSuperContributionsTableData = [];
let jsonData;
// commence for loop at 1 because the first row will be the header row and we want to skip that
for (let i = 1; i < table.rows.length; i++) {
let row = table.rows[i];
// first check all cells in row have a value, if not ignore
if (row.cells[0].innerText !== "" && row.cells[1].innerText !== "" && row.cells[2].innerText !== "") {
// As we are pushing the last element pushed becomes the first element in the array
// therefore, we push the before or after tax first and age last
jsonData = {};
jsonData[SUPER_TAXATION_CONTRIBUTION] = row.cells[2].innerText;
jsonData[SUPER_AMOUNT_CONTRIBUTION] = row.cells[1].innerText;
jsonData[SUPER_AGE_CONTRIBUTION] = row.cells[0].innerText;
yourSuperContributionsTableData.push(jsonData);
}
}
return yourSuperContributionsTableData;
}
Where I went wrong with this originally was I stringified the array. As the entire javascript object is going to be stringified this was unnecessary.
Create javascript object and store in local storage
The first step is to extract the item from local storage to update it with the new data from the user. Notice we must parse the object because it was originally stringified.
Secondly set the user entered data on the javascript object. You will notice the call to the function above that retrieves the table data. That table data is set as a key value pair in the javascript object.
const scenarioName = localStorage.getItem(ACTIVE_SCENARIO_KEY);
const object = localStorage.getItem(scenarioName);
let scenarioObject = JSON.parse(object);
isValid = validateYourSuperannuationForm();
if (isValid) {
let superContributionsTableDataString = getSuperContributionsTableDataString(
document.getElementById("your-extra-super-contributions-table"));
scenarioObject.SUPER_BALANCE = $("#your-super-balance").val();
scenarioObject.SUPER_INVESTMENT_FEES = $("#super-investment-fees").val();
scenarioObject.SUPER_ADMIN_FEES = $("#super-admin-fees").val();
scenarioObject.LIFE_INSURANCE = $("#life-insurance").val();
scenarioObject.ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION = $("#your-annual-lump-sum-super-contribution").val();
scenarioObject.EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA = superContributionsTableDataString;
let objectString = JSON.stringify(scenarioObject);
localStorage.setItem(scenarioName, objectString);
}
Send item in local storage to server
I discovered trying to stringify the entire javascript object caused problems at the server. What I had to do was create a new object for the formData to be sent to the server, BUT I had to stringify only the table data, not the entire object. I had to retrieve each item from local storage and set it on the formData object to be passed to the server.
function sendScenarioDetailsToServer() {
const activeScenario = localStorage.getItem(ACTIVE_SCENARIO_KEY);
const item = localStorage.getItem(activeScenario);
const scenarioObject = JSON.parse(item);
// We must do this because if superContributionsTableData == "" and we then stringify this it will
// end up with a value of """", which will cause an error.
const superContributionsTableData = scenarioObject.EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA;
let superContributionsTableDataString = "";
if (superContributionsTableData !== ""){
superContributionsTableDataString = JSON.stringify(superContributionsTableData);
}
const formData = {
SCENARIO_NAME: scenarioObject.SCENARIO_NAME,
DATE_OF_BIRTH: "",
IS_SINGLE: scenarioObject.IS_SINGLE,
IS_RETIRED: scenarioObject.IS_RETIRED,
RETIREMENT_DATE: scenarioObject.RETIREMENT_DATE,
IS_HOMEOWNER: scenarioObject.IS_HOMEOWNER,
FORTNIGHTLY_RENT: scenarioObject.FORTNIGHTLY_RENT,
DATE_RENT_CEASES: scenarioObject.DATE_RENT_CEASES,
IS_SINGLE_AND_SHARING: scenarioObject.IS_SINGLE_AND_SHARING,
SPOUSE_DATE_OF_BIRTH: scenarioObject.SPOUSE_DATE_OF_BIRTH,
IS_SPOUSE_RETIRED: scenarioObject.IS_SPOUSE_RETIRED,
SPOUSE_RETIREMENT_DATE: scenarioObject.SPOUSE_RETIREMENT_DATE,
SUPER_BALANCE: scenarioObject.SUPER_BALANCE,
SUPER_INVESTMENT_FEES: scenarioObject.SUPER_INVESTMENT_FEES,
SUPER_ADMIN_FEES: scenarioObject.SUPER_ADMIN_FEES,
LIFE_INSURANCE: scenarioObject.LIFE_INSURANCE,
ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION: scenarioObject.ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION,
EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA: superContributionsTableDataString
}
$.ajax({
type: "POST",
url: "ScenarioServlet",
data: formData,
success: function (data) {
// do stuff here
{
},
error: function (error, status) {
console.log(`Error ${error}`);
const stackTrace = getStackTrace();
const message = "An error occurred sending your data to the server for calculation. ";
displayPopupMessage(message, "Server Error.", stackTrace);
}
});
In the Java Servlet the data is then extracted from the HttpServletRequest passed to the doPost method. It is retrieved in the usual way by calling HttpServletRequest.getParameter. Converting the table data is a little more complex because it is an array that was converted to a string. I am including an extract of that code in case it is of use to someone.
ArrayList<LumpSumSuperContribution> superContributionsList = new ArrayList<>();
String superContributionsTableData = request.getParameter(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA);
// Array superContributionsArray = request.getParameter(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA);
JSONObject superContributionsMessage = new JSONObject();
boolean errorOccurred = false;
if (superContributionsTableData != null && superContributionsTableData.length() > 0) {
try {
JSONArray superContributionsArray = new JSONArray(superContributionsTableData);
int i = 0;
while (i < superContributionsArray.length()) {
JSONObject contributionObj = (JSONObject) superContributionsArray.get(i);
String ageString = (String) contributionObj.get(SUPER_AGE_CONTRIBUTION);
Validator.WholeNumberResult result6 = Validator.validateMandatoryWholeNumber(ageString, 18, 99,
"Lump Sum Super Contribution age for row " + (i + 1));
if (!result6.getErrorMessage().equals(SUCCESS)) {
superContributionsMessage.put(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA, result6.getErrorMessage());
messageArray.put(superContributionsMessage);
errorOccurred = true;
break;
}
Integer age = result6.getNumber();
String contributionAmountString = (String) contributionObj.get(SUPER_AMOUNT_CONTRIBUTION);
Validator.WholeNumberResult result7 = Validator.validateMandatoryWholeNumber(
contributionAmountString, 1, 9999999,
"Lump Sum Super Contribution amount for row " + (i + 1));
if (!result7.getErrorMessage().equals(SUCCESS)) {
superContributionsMessage.put(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA, result7.getErrorMessage());
messageArray.put(superContributionsMessage);
errorOccurred = true;
break;
}
Integer amount = result7.getNumber();
String beforeAfterTaxString = (String) contributionObj.get(SUPER_TAXATION_CONTRIBUTION);
Validator.TextResult result8 = Validator.validateMandatoryText(beforeAfterTaxString,
"Lump Sum Super Contribution Before or After Tax for row " + (i + 1), 5, 6);
if (!result8.getErrorMessage().equals(SUCCESS)) {
superContributionsMessage.put(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA, result8.getErrorMessage());
messageArray.put(superContributionsMessage);
errorOccurred = true;
break;
}
String beforeAfterTax = result8.getText();
LumpSumSuperContribution superContribution = new LumpSumSuperContribution(age, amount, false,
LumpSumSuperContribution.YOUR_CONTRIBUTION, beforeAfterTax);
superContributionsList.add(superContribution);
i++;
}
if (!errorOccurred) {
scenario.setAllYourSuperContributions(superContributionsList);
// superContributionsMessage.put(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA, SUCCESS);
} else {
fail = true;
superContributionsMessage.put(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA, FAIL);
messageArray.put(superContributionsMessage);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}else {
scenario.setAllYourSuperContributions(null);
}
}
Summary
Create a javascript array. Then loop through the table data and create a javascript object for each row of the table and push onto the array.
Create or retrieve javascript object stored in local storage. If already in local storage, this object must be parsed using JSON.parse(object).
Set the details on the object entered by the user.
Stringify the javascript array and add the string to the object as a key value pair.
To send the data to the server retrieve the item from local storage and parse the item to extract details from it.
Set the extracted details on a newly created formData object.
Stringify the table data and set as a key value pair in formData.
Using ajax Post the data to the server.
I hope this helps someone in the future. It took me a while of trying different things to find a way to get this to work. If anyone has a better solution please post it.

How to read JSON Response from URL and use the keys and values inside Javascript (array inside array)

My Controller Function:
public function displayAction(Request $request)
{
$stat = $this->get("app_bundle.helper.display_helper");
$displayData = $stat->generateStat();
return new JsonResponse($displayData);
}
My JSON Response from URL is:
{"Total":[{"date":"2016-11-28","selfies":8},{"date":"2016-11-29","selfies":5}],"Shared":[{"date":"2016-11-28","shares":5},{"date":"2016-11-29","shares":2}]}
From this Response I want to pass the values to variables (selfie,shared) in javascript file like:
$(document).ready(function(){
var selfie = [
[(2016-11-28),8], [(2016-11-29),5]]
];
var shared = [
[(2016-11-28),5], [(2016-11-29),2]]
];
});
You can try like this.
First traverse the top object data and then traverse each property of the data which is an array.
var data = {"total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2},{"date":"2016-11-30","selfies":0},{"date":"2016-12-01","selfies":0},{"date":"2016-12-02","selfies":0},{"date":"2016-12-03","selfies":0},{"date":"2016-12-04","selfies":0}],"shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0},{"date":"2016-11-30","shares":0},{"date":"2016-12-01","shares":0},{"date":"2016-12-02","shares":0},{"date":"2016-12-03","shares":0},{"date":"2016-12-04","shares":0}]}
Object.keys(data).forEach(function(k){
var val = data[k];
val.forEach(function(element) {
console.log(element.date);
console.log(element.selfies != undefined ? element.selfies : element.shares );
});
});
Inside your callback use the following:
$.each(data.total, function(i, o){
console.log(o.selfies);
console.log(o.date);
// or do whatever you want here
})
Because you make the request using jetJSON the parameter data sent to the callback is already an object so you don't need to parse the response.
Try this :
var text ='{"Total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2}],"Shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0}]}';
var jsonObj = JSON.parse(text);
var objKeys = Object.keys(jsonObj);
for (var i in objKeys) {
var totalSharedObj = jsonObj[objKeys[i]];
if(objKeys[i] == 'Total') {
for (var j in totalSharedObj) {
document.getElementById("demo").innerHTML +=
"selfies on "+totalSharedObj[j].date+":"+totalSharedObj[j].selfies+"<br>";
}
}
if(objKeys[i] == 'Shared') {
for (var k in totalSharedObj) {
document.getElementById("demo").innerHTML +=
"shares on "+totalSharedObj[k].date+":"+totalSharedObj[k].shares+"<br>";
}
}
}
<div id="demo">
</div>
I did a lot of Research & took help from other users and could finally fix my problem. So thought of sharing my solution.
$.get( "Address for my JSON data", function( data ) {
var selfie =[];
$(data.Total).each(function(){
var tmp = [
this.date,
this.selfies
];
selfie.push(tmp);
});
var shared =[];
$(data.Shared).each(function(){
var tmp = [
this.date,
this.shares
];
shared.push(tmp);
});
});

how to get Datatable data and check with new data to remove duplicate?

I am working on DataTable jquery plugin. i need to remove the duplicate value with check the comming value is alrady in the datatable and update the data dynamically in the datatable.
function checkDuplicate(newResource) {
var resource = $('#list').DataTable();
var oldResources = resource.rows().data();
var stringArr = JSON.stringify(oldResources),
result = newResource.filter(function (obj) {
var stringObj = JSON.stringify(obj);
if (stringArr.indexOf(stringObj) != -1)
return true;
else
return false;
});
if(result.length != 0){
resource.rows.add(result).draw(false);
}
}
But there is a error
Uncaught TypeError: Converting circular structure to JSON
how to solve this problem.

Reading unlabelled JSON arrays

I am trying to pull data, using JQuery, out of an unlabelled array of unlabelled objects (each containing 4 types of data) from a JSON api feed. I want to pull data from the first or second object only. The source of my data is Vircurex crypto-currency exchange.
https://api.vircurex.com/api/trades.json?base=BTC&alt=LTC
By 'unlabelled' I mean of this format (objects without names):
[{"date":1392775971,"tid":1491604,"amount":"0.00710742","price":"40.0534"},{ .... }]
My Javascript look like this:
var turl = 'https://api.vircurex.com/api/trades.json?base=BTC&alt=LTC';
$.getJSON(turl, function (data) {
$.each(data, function(key,obj) {
var ticker1tid = obj[1].tid;
var ticker1amount = obj[1].amount;
var ticker1date = obj[1].date;
var ticker1price = obj[1].price;
});
});
Somehow I am not calling in any data using this. Here is link to my sand-box in JSFiddle: http://jsfiddle.net/s85ER/2/
If you just need the second element in the array, remove the traversing and access it directly from the data:
var turl = 'https://api.vircurex.com/api/trades.json?base=BTC&alt=LTC';
$.getJSON(turl, function (data) {
var ticker1tid = data[1].tid;
var ticker1amount = data[1].amount;
var ticker1date = data[1].date;
var ticker1price = data[1].price;
// Or isn't it better to just have this object?
var ticker = data[1];
ticker.tid // 1491736
ticker.amount // 0.01536367
// etc
});

Is there a Jquery function that can take a #ref id value from a parsed JSON string and point me to the referenced object?

I have been looking for an answer to this all afternoon and i cant seem to find the best way to accomplish what i need to.
My JSON string (returned from a web service) has circular references in it (#ref) which point to $id in the string. Now i know that if use jquery parseJSON it creates the javascript object and i can access properties a la myObject.MyPropertyName. However, when i get to a #ref, i am unsure how to get the object that ID points to (which i assume is already created as a result of the de-serialization...
Should i be iterating though the object and all its child objects until i find it, or is there an easier way?
$.ajax({
type: "POST",
url: "/Task.asmx/GetTask",
data: "{'id':'" + '27' + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
_Data = $.parseJSON(msg.d ? msg.d : msg);
_this.Company = _Data[0].t_Program.t_Company;
_this.Program = _Data[0].t_Program;
_this.Task = _Data[0];
},
complete: function () {
}
});
The area in question is _Data[0].t_Program because it does not return an object but rather returns
_Data[0].t_Program
{...}
$ref: "12"
I dont exactly know the best way to get the object with $id "12". Based on the posts below it seems i should loop through the existing object, but i was hoping there was a jquery function that did that...
Many Thanks!
No, jQuery is not natively capable of resolving circular references in objects converted from JSON.
The only library for that which I know is Dojo's dojox.json.ref module.
But, your server application serializes that JSON somehow. Don't tell me that the solution it uses does not offer a deserialisation algorithm!
As my friend Alan, the author of the Xerox Courier (RPC over the net) library, used to say to me, "there are no pointers on the wire."
In other words, it is impossible for a JSON representation of a data structure to be circular. (But a circular structure can be flattened into a non-circular JSON structure.) As the JSON site says:
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
No pointers!
So the entire JSON will have been turned into Javascript Objects and/or Arrays after the jQuery parseJSON operation completes.
If the original stucture's ref_id values were used as the property names in the JSON / Javascript object, then they'll all be there.
The real issue is that you need to understand how your server serialized its data structure into the JSON data structure. Look in your server-side code to determine that.
Then use Javascript to de-serialize the JSON structure back into the best Javascript structure to fit your needs.
Re: Should i be iterating though the object and all its child objects until i find it, or is there an easier way?
The easier way would be to go through the Javascript structure once, and build up an additional "indexing" object whose properties are the #ref_id and the values are the original structure/value.
Sample:
var jsonCyclicReferenceFixed = JsonRecursive.parse(jsonWithRefAndId);
(function(){
function type(value){
var t = typeof(value);
if( t == "object" && value instanceof Array) {
return "array";
}
if( t == "object" && value && "$id" in value && "$values" in value) {
return "array";
}
return t;
}
function TypeConverterFactory(){
var converters = {};
var defaultConverter = {
fromJson: function(value){ return value; },
toJson: function(value){ return value; },
};
this.create = function(type){
var converter = converters[type];
if(!converter) return defaultConverter;
return converter;
};
this.register = function(type, converter){
converters[type] = converter;
converter.valueConverter = this.valueConverter;
};
}
function ObjectConverter(){
this.fromJson = function(obj){
if( obj == null ) return null;
if( "$ref" in obj ){
var reference = this.dictionary[obj.$ref];
return reference;
}
if("$id" in obj){
this.dictionary[obj.$id] = obj;
delete obj.$id;
}
for(var prop in obj){
obj[prop] = this.valueConverter.convertFromJson(obj[prop]);
}
return obj;
}
this.toJson = function(obj){
var id = 0;
if(~(id = this.dictionary.indexOf(obj))){
return { "$ref" : (id + 1).toString() };
}
var convertedObj = { "$id" : this.dictionary.push(obj).toString() };
for(var prop in obj){
convertedObj[prop] = this.valueConverter.convertToJson(obj[prop]);
}
return convertedObj;
}
}
function ArrayConverter(){
var self = this;
this.fromJson = function(arr){
if( arr == null ) return null;
if("$id" in arr){
var values = arr.$values.map(function(item){
return self.valueConverter.convertFromJson(item);
});
this.dictionary[arr.$id] = values;
delete arr.$id;
return values;
}
return arr;
}
this.toJson = function(arr){
var id = 0;
if(~(id = this.dictionary.indexOf(arr))){
return { "$ref" : (id + 1).toString() };
}
var convertedObj = { "$id" : this.dictionary.push(arr).toString() };
convertedObj.$values = arr.map(function(arrItem){
return self.valueConverter.convertToJson(arrItem);
});
return convertedObj;
}
}
function ValueConverter(){
this.typeConverterFactory = new TypeConverterFactory();
this.typeConverterFactory.valueConverter = this;
this.typeConverterFactory.register("array", new ArrayConverter);
this.typeConverterFactory.register("object", new ObjectConverter);
this.dictionary = {};
this.convertToJson = function(valor){
var converter = this.typeConverterFactory.create(type(valor));
converter.dictionary = this.dictionary;
return converter.toJson(valor);
}
this.convertFromJson = function(valor){
var converter = this.typeConverterFactory.create(type(valor));
converter.dictionary = this.dictionary;
return converter.fromJson(valor);
}
}
function JsonRecursive(){
this.valueConverter = new ValueConverter();
}
JsonRecursive.prototype.convert = function(obj){
this.valueConverter.dictionary = [];
var converted = this.valueConverter.convertToJson(obj);
return converted;
}
JsonRecursive.prototype.parse = function(string){
this.valueConverter.dictionary = {};
var referenced = JSON.parse(string);
return this.valueConverter.convertFromJson(referenced);
}
JsonRecursive.prototype.stringify = function(obj){
var converted = this.convert(obj);
var params = [].slice.call(arguments, 1);
return JSON.stringify.apply(JSON, [converted].concat(params));
}
if(window){
if( window.define ){
//to AMD (require.js)
window.define(function(){
return new JsonRecursive();
});
}else{
//basic exposition
window.jsonRecursive = new JsonRecursive();
}
return;
}
if(global){
// export to node.js
module.exports = new JsonRecursive();
}
}());
Sample:
// a object recursive
// var parent = {};
// var child = {};
// parent.child = child;
// child.parent = parent;
//
//results in this recursive json
var json = '{"$id":"0","name":"Parent","child":{"$id":"1","name":"Child","parent":{"$ref":"0"}}}'
//Parsing a Recursive Json to Object with references
var obj = jsonRecursive.parse(json);
// to see results try console.log( obj );
alert(obj.name);
alert(obj.child.name);

Categories

Resources