JavaScript map containing arrays turns into map containing maps - javascript

I am creating a map containing arrays.
I'm sending this map as parameter to a method in a popup window.
This map of arrays is turning into a map of maps in the popup window!!
Im using IE8.
I'm creating a map like this:
var mapDetails = new Object();
mapDetails.fields = ['A','B'];
mapDetails.optSampleData = ['X','Y'];
JSON of map Im sending:
{'fields':['A','B'],'optSampleData':['X','Y']}
JSON of map Im receiving:
{'fields':{'0':'A','1':'B'},'optSampleData':{'0':'X','1':'Y'}}
This wouldnt be a problem in JS as the data can still be accessed as fields[0]. But, I'm sending it to server-side where I'm using GSON to parse the JSON. GSON turns it into a map.

Try this function
function myParser(str) {
str = str.replace(/'/g, '"');
var obj = JSON.parse(str);
for(var item in obj) {
if(obj.hasOwnProperty(item)) {
var array = [];
for(var arrItem in obj[item]) {
if(obj[item].hasOwnProperty(arrItem)) {
array.push(obj[item][arrItem]);
}
}
obj[item] = array;
}
}
return obj;
}
You can pass the received string into this function and receive your desired map containing arrays
Also you can reform your received string into your desired string format by this function:
var str = "{'fields':{'0':'A','1':'B'},'optSampleData':{'0':'X','1':'Y'}}";
var obj = myParser(str);
var desiredFormat = JSON.stringify(obj);
/* The result would be: */
/* "{"fields":["A","B"],"optSampleData":["X","Y"]}" */
Hope it helps you :)

Related

how to parse a json data with multiple values?

i have a multidimensional json . i want to parse it to get the values.
var json='{"Links":[],"RequestedObject":{"FieldContents":{"21514":{"Type":1,"IsError":false,"Value":"Saneen","FieldId":21514,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21516":{"Type":1,"IsError":false,"Value":"English","FieldId":21516,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21517":{"Type":1,"IsError":false,"Value":"Malayalam","FieldId":21517,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21515":{"Type":2,"IsError":false,"Value":26.0,"FieldId":21515,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21518":{"Type":2,"IsError":false,"Value":80.0,"FieldId":21518,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21519":{"Type":2,"IsError":false,"Value":40.0,"FieldId":21519,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21520":{"Type":4,"IsError":false,"Value":{"ValuesListIds":[72639],"OtherText":null},"FieldId":21520,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21523":{"Type":3,"IsError":false,"Value":"2017-03-29T00:00:00","FieldId":21523,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21510":{"Type":6,"FieldId":21510,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21511":{"Type":21,"FieldId":21511,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21512":{"Type":22,"FieldId":21512,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21521":{"Type":11,"Value":null,"FieldId":21521,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}}}},"IsSuccessful":true,"ValidationMessages":[]}';
i have tried with JSON.parse , but no luck.
Here is an simple example of JSON.parse() and here is document for that:
var json='{"Links":[],"RequestedObject":{"FieldContents":{"21514":{"Type":1,"IsError":false,"Value":"Saneen","FieldId":21514,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21516":{"Type":1,"IsError":false,"Value":"English","FieldId":21516,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21517":{"Type":1,"IsError":false,"Value":"Malayalam","FieldId":21517,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21515":{"Type":2,"IsError":false,"Value":26.0,"FieldId":21515,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21518":{"Type":2,"IsError":false,"Value":80.0,"FieldId":21518,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21519":{"Type":2,"IsError":false,"Value":40.0,"FieldId":21519,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21520":{"Type":4,"IsError":false,"Value":{"ValuesListIds":[72639],"OtherText":null},"FieldId":21520,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21523":{"Type":3,"IsError":false,"Value":"2017-03-29T00:00:00","FieldId":21523,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21510":{"Type":6,"FieldId":21510,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21511":{"Type":21,"FieldId":21511,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21512":{"Type":22,"FieldId":21512,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}},"21521":{"Type":11,"Value":null,"FieldId":21521,"UpdateInformation":{"CreateDate":null,"UpdateDate":null,"CreateLogin":null,"UpdateLogin":null}}}},"IsSuccessful":true,"ValidationMessages":[]}';
var obj = JSON.parse(json);
console.log(obj);
// retrieve particular fields
var newFieldContents = {};
for(var key in obj['RequestedObject']['FieldContents']){
var o = obj['RequestedObject']['FieldContents'][key];
newFieldContents[key] = {
Value: o['Value'],
FieldId: o['FieldId']
}
}
console.log(newFieldContents);
Update
Add how to retrieve particular fields.

JSON rows Extracting issue in JavaScript

I have following json data coming from server in which i want to extract LimitClass and LimitClassID and store their values in respective arrays.
{
"ErrorDesc":"",
"ErrorCode":"",
"LimitClassList":"[{\"LimitClass\":\"L16\\n\",\"LimitClassId\":\"32900\\n\"},{\"LimitClass\":\"28febL0\\n\",\"LimitClassId\":\"31901\\n\"},{\"LimitClass\":\"L14\\n\",\"LimitClassId\":\"31900\\n\"},{\"LimitClass\":\"L17\\n\",\"LimitClassId\":\"32950\\n\"},{\"LimitClass\":\"L15\\n\",\"LimitClassId\":\"31950\\n\"},{\"LimitClass\":\"L0\\n\",\"LimitClassId\":\"21901\\n\"},{\"LimitClass\":\"L4\\n\",\"LimitClassId\":\"23000\\n\"},{\"LimitClass\":\"OTC Send\\n\",\"LimitClassId\":\"30901\\n\"},{\"LimitClass\":\"L2\\n\",\"LimitClassId\":\"22900\\n\"},{\"LimitClass\":\"L12\\n\",\"LimitClassId\":\"28900\\n\"},{\"LimitClass\":\"L6\\n\",\"LimitClassId\":\"23900\\n\"},{\"LimitClass\":\"L1\\n\",\"LimitClassId\":\"25900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"29900\\n\"},{\"LimitClass\":\"L7\\n\",\"LimitClassId\":\"24900\\n\"},{\"LimitClass\":\"L8\\n\",\"LimitClassId\":\"26900\\n\"},{\"LimitClass\":\"L10\\n\",\"LimitClassId\":\"27900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"30900\\n\"},{\"LimitClass\":\"UatTesting123\\n\",\"LimitClassId\":\"32901\\n\"}]"
}
Here is the code I have tried :
var list = data.LimitClassList;
var arrayLimitClass = [];
var arrayLimitClassId = [];
for(var i in list) {
arrayLimitClass.push(list[i].LimitClass);
arrayLimitClassId.push( list[i].LimitClassId);
}
alert(list);
alert(arrayLimitClass);
alert(arrayLimitClassId);
List variable has following result when I alert it:
[{\"LimitClass\":\"L16\\n\",\"LimitClassId\":\"32900\\n\"},{\"LimitClass\":\"28febL0\\n\",\"LimitClassId\":\"31901\\n\"},{\"LimitClass\":\"L14\\n\",\"LimitClassId\":\"31900\\n\"},{\"LimitClass\":\"L17\\n\",\"LimitClassId\":\"32950\\n\"},{\"LimitClass\":\"L15\\n\",\"LimitClassId\":\"31950\\n\"},{\"LimitClass\":\"L0\\n\",\"LimitClassId\":\"21901\\n\"},{\"LimitClass\":\"L4\\n\",\"LimitClassId\":\"23000\\n\"},{\"LimitClass\":\"OTC Send\\n\",\"LimitClassId\":\"30901\\n\"},{\"LimitClass\":\"L2\\n\",\"LimitClassId\":\"22900\\n\"},{\"LimitClass\":\"L12\\n\",\"LimitClassId\":\"28900\\n\"},{\"LimitClass\":\"L6\\n\",\"LimitClassId\":\"23900\\n\"},{\"LimitClass\":\"L1\\n\",\"LimitClassId\":\"25900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"29900\\n\"},{\"LimitClass\":\"L7\\n\",\"LimitClassId\":\"24900\\n\"},{\"LimitClass\":\"L8\\n\",\"LimitClassId\":\"26900\\n\"},{\"LimitClass\":\"L10\\n\",\"LimitClassId\":\"27900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"30900\\n\"},{\"LimitClass\":\"UatTesting123\\n\",\"LimitClassId\":\"32901\\n\"}]
But I am getting dots (.) when I alert arrayLimitClass and arrayLimitClassId. What am I doing wrong in extracting rows of json Object?
"LimitClassList":"[{\"LimitClass\":\"L1....]"
^ ^
LimitClassList is a string, not an array. Make it so it is an actual array, than your code should work. There should be no reason to have to parse it again.
The value below data.LimitClassList is itself a String containing JSON. You have to decode this first.
var list = JSON.parse( data.LimitClassList );
var arrayLimitClass = [];
var arrayLimitClassId = [];
// ...
This is more or less a workaround. You should have a look at your server code and fix the encoding error there!

How do I force jsonStringify to output an array without quotes?

I am using a Google Apps script to format data from a Google spreadsheet into geoJSON by calling jsonStringify. My code is modified from this original example. Each row in the spreadsheet represents a country, with a single cell containing the relevant geoJSON polygon data:
[[[74.92,37.24],[74.57,37.03],...[73.31,37.46],[74.92,37.24]]]
But since that cell doesn't contain a number, jsonStringify is parsing it as a string, returning this:
"coordinates":["[[[74.92,37.24],[74.57,37.03],...[73.31,37.46],[74.92,37.24]]]"]
...which I can't use, since the quotes make it non-valid geoJSON. When I enter a single number, jsonStringify returns it without the quotes, I assume because it recognizes that it's a number. Is there some way I can force it to interpret the polygon data as a number or otherwise escape the quotes? Here is the relevant section of my code:
function getObjects(data, keys) {
var objects = [];
var headers = getHeaders(sheet, activeRange, 1);
var zip = function(keys, data) {
var obj = {};
for (var i = 0; i < keys.length; i++) {
obj[keys[i]] = data[i];
}
return obj;
};
for (var i = 0; i < data.length; i++) {
var obj = zip(headers, data[i]);
//this is the polygon data
var poly = obj[settings.poly];
var coordinates = [poly];
// If we have an id and polygon data
if (obj[settings.id] && poly) {
// Define a new GeoJSON feature object
var feature = {
type: 'Feature',
// Get ID from UI
id: obj[settings.id],
geometry: {
type: 'MultiPolygon',
// Get coordinates from UIr
coordinates: coordinates
},
// Place holder for properties object
properties: obj
};
objects.push(feature);
}
}
return objects;
}
Instead of passing a string to jsonStringify as the "coordinates", pass an actual array. That is, use jsonParse first on the original text (as required) to obtain the relevant object.
An example conversion (with guard that may or may not be appropriate) might look like:
function restoreCoordinatesFromText(source) {
var geo = Utilities.jsonParse(source);
return (geo && (geo instanceof Array)
? geo // looks like we got our [array of stuff]
: theSourceData); // dunno, let's act like we never saw it
}
Then later on the actual coordinate array can be encoded correctly in JSON while the string exhibits the initial undesired behavior.
var coords = "[1,2,3,4]"; /* just a string */
var json = Utilities.jsonStringify({
/* array, good! */
goodCoordinates: restoreCoordinatesFromText(coords),
/* string, bad! */
badCoordinates: coords
});
Here is the corresponding fiddle (it utilizes ES5 JSON support).

How to fetch data from JSON object in JavaScript?

I am working on SpringMVC. In my controller I create a JSON object and I pass that object to JavaScript. How can I read that object in JavaScript?
My Map object
Map<String rootNode,List<String>> map = new HashMap<String rootNode,List<String>();
String rootNode = "bhanu";
ArrayList<String> al = new ArrayList<String>();
for( int i = 0; i < UserProfile.size; i++ ) {
al.add( userProfile.get( i ) );
}
map.put( userProfile, al );
At last my Map object has this data:
{
"Bhanu":["hari#gmail.com","balu#gmail.com","santha#gmail.com"],
"root":["bhanu#gmail.com","anu#gmail.com","apar#gmail.com"],
"hari":["bhanuprasad#gmail.com","sravya#gmail.com","mahesh#gmail.com"],
"balu":["rama#gmail.com"]
}
Now I convert this object with GSon:
Gson gson = new GSon();
String orgChartUsers = gson.toJson(map);
Now I passed this string to JavaScript because this is my Ajax response:
function orgUsers( result ) {
var orgObject = JSON.parse( result );
for(var name in result) {
console.log(name + "=" + result[name]);
}
}
This is working fine but i want to fetch data like this
first i want to fetch data from "root" in root i have some data when i read root for example i got bhanu#gmail.com now i want to fetch the data from Bhanu here i got some data like hari#gmail.com again i want to fetch data for hari like this i want how can i do this any one help me
Your lists will become javascript arrays, so for example you could use:
window.alert (orgObject["Bhanu"][0]);
which should pop up "hari#gmail.com" given your example data.
See How to list the properties of a JavaScript object for details of how to list the keys of your map, should you need this.
The result will be either an object or array.
To iterate over objects you can use the for-in loop
for (var key in obj) {
if(obj.hasOwnProperty(key)) {
// do something here
}
}
To iterate over an array you can use a normal loop:
for (var i = 0, ilen = array.length; i < ilen; i += 1) {
// do something here
}
Here is the most simple way
var result = {"Bhanu":["hari#gmail.com","balu#gmail.com","santha#gmail.com"],"root":["bhanu#gmail.com","anu#gmail.com","apar#gmail.com"],"hari":["bhanuprasad#gmail.com","sravya#gmail.com","mahesh#gmail.com"],"balu":["rama#gmail.com"]};
for(var name in result) {
console.log(name + "=" + result[name]);
}
This outputs:
Bhanu=hari#gmail.com,balu#gmail.com,santha#gmail.com
root=bhanu#gmail.com,anu#gmail.com,apar#gmail.com
hari=bhanuprasad#gmail.com,sravya#gmail.com,mahesh#gmail.com
balu=rama#gmail.com
Have in mind that the arrays are actually cast to a string. So result[name] is actually an array.

Creating hash array in Google Apps Script

I've been trying to work with Trello and the Google Apps Script this week. I am trying to create an array of hashes that I can then use to load the spreadsheet. Google apps script doesn't like the typical javascript code of creating hashes. I've looked up the docs but they don't have anything like hashes...they say to:
var object = [];
var object1 = {};
object.push(object1);
This wont work because I'm essentially trying to do something like:
var hash={name: , label: };
var n= someNumber;
var l= someLabel
var hash.push(name: n, label: l);
Essentially that is the code I have right now. But here is my entire function:
function getData(){
var list={};
//get the list of delivered cards from Trello
var listRequest = authorizeToTrello(); // get authorization
var result = UrlFetchApp.fetch("https://trello.com/1/lists/4fea3a2c3a7038911ebff2d8/cards",
listRequest);//fetch list
var listOfCards = Utilities.jsonParse(result.getContentText());//Google app utility format json
//outer loop to iterate through list of Cards
for(var i=0; i < listOfCards.length; i++){
var cardId = listOfCards[i].id; //get the id of a single card
var l = listOfCards[i]["label"]; //get the label for the our structure
//get a json object for a single card within the list of cards iteration
var cardRequest = authorizeToTrello();
var getCard = UrlFetchApp.fetch("https://trello.com/1/cards/" + cardId + "/actions", cardRequest);
var singleCard = Utilities.jsonParse(getCard.getContentText());
//inner loop to iterate the single cards JSON objects
for(var j=0; j < singleCard.length; j++) {
if(singleCard[j].data != undefined && singleCard[j].data.listAfter != undefined)
{
var str = singleCard[j]["data"]["listAfter"]['name'];
if(str === "Delivered Q3 2012"){
var n = singleCard[j]['memberCreator']['fullName'];
}
}
}
//push the data to list
list.push(n,l);
}
return name, label; //return list for output
}
Reading the question, I understood that the author needs to know how to create an associative array in a GAS. If it is correct then here is a couple of links (here and here) and a sample code is bellow.
function testMap() {
var map = {};
map["name1"] = "value1";
map["name2"] = "value2";
return map;
}
If the author needs really
an array of hashes
then there are a couple of ways depending on which hash algorithm is required.
to use the Utilities.computeDigest method to calculate a hash of a string using one of available algorithms.
if the required hash calculation algorithm is not supported by the Utilities.computeDigest, then is possible to write own implementation as it is done for the BLAKE function.
Here is a sample of how to create an array of hashes using the MD5 hash.
function testHash() {
var array = [];
array.push(Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, "value1"));
array.push(Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, "value2"));
return array;
}
P.S. The return line of the author code return name, label; //return list for output
is not correct - only the label variable value is returned. To return a couple of variables as an array is necessary to write return [name, label];. Or may be the author needs to return the list variable and not name and label.
I know this is an old post / question, but i would like to update my answer since the original anwer (1st answer) is misleading. I was myself looking for how to return associative arrays back to a cell in the spreadsheet, but alas.. "YOU CANNOT". Google spreadsheet MUST want an numerically indexed array or an object. Otherwise it returns "#ERROR".
Here are the steps to replicate the issue.
function testMap() {
var map = {};
map["name1"] = "value1";
map["name2"] = "value2";
return map
Formula in your cell: =testMap()
Value in your cell: Thinking... #ERROR
Solution (rather a workaround)
1: Transfer your objects from your associative array into a numerically indexed array using for-each type loop.
var temp = new Array();
for (var i in map) {
temp.push([i,map[i]])
// optionally use activeSheet.getRange(X:X).setValue([i,map[i]])) function here.
// set values will not work in cell functions. To use it via cell functions, rerun / trigger the functions using an on_edit event.
}
If you used a temp like numerically indexed array, you can return "temp" back to the calling cell.
Summary: For onEdit() purposes, use Cache Service to define associative array data.
Here's a shared Gsheet demonstrating this curious behavior. I tried the following solution in programmatically defining an associative array based on data in a Google sheet.
var assocArr = {
labels: {},
init: function () {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('sheetName');
var values = sheet.getDataRange().getValues();
for(var row in values) {
assocArr.labels[values[row][0]] = values[row][1];
};
for(var key in assocArr.labels) {
Logger.log("key: %s, value: %s",key, assocArr.labels[key]);
};
return(void(0));
},
};
To execute this, you run the init() method in the onOpen() event handler.
function onOpen() {
assocArr.init();
var key = 'test';
SpreadsheetApp.getUi().alert( assocArr.labels[key] );
Logger.log("onOpen: key: %s, value: %s",key, assocArr.labels[key]);
};
The logger message confirms that init() loads the data from the worksheet.
Now if I try to reference this assocArr object in onEdit() it returns undefined for all key values.
function onEdit(event) {
var key = 'test';
SpreadsheetApp.getUi().alert( assocArr.labels[key] );
Logger.log("onEdit: key: %s, value: %s",key, assocArr.labels[key]);
};
I infer that for security reasons, Google limited the simple-trigger onEdit() to not have global variable scope, same as they voided the utility of the event.user property.
Now instead if I simply put the key-value pair in the cache, it works! Here is the complete code that works using the Cache Service.
var cache = CacheService.getPrivateCache();
var assocArr = {
init: function () {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Account Labels');
var values = sheet.getDataRange().getValues();
for(var row in values) {
cache.put(values[row][0], values[row][1], 3600);
};
return(void(0));
},
};
function onOpen() {
assocArr.init();
var key = 'test';
SpreadsheetApp.getUi().alert( cache.get(key) );
Logger.log("onOpen: key: %s, value: %s",key, cache.get(key));
};
function onEdit(event) {
var key = 'test';
SpreadsheetApp.getUi().alert( cache.get(key) );
Logger.log("onEdit: key: %s, value: %s",key, cache.get(key));
};
Curiously, the onEdit() has the cache variable in its scope.
Here again is the shared Gsheet demonstrating this curious behavior.
I found this really quick way that is not listed
Create a json object (array style)
var myArray = {
1:{"id": "inprogress","title" : "in Progress"},
2:{"id": "notstarted","title" : "Not Started"},
3:{"id": "completed" ,"title" : "Completed"}
};
read the json
// get the lenght of the json object
var jsonSize = Object.keys(myArray).length;
// use this in a loop
for (var i = 1; i < Object.keys(jsonSize).length; i++) {
var title = myArray[i].title;
}
Works like a charm for me

Categories