Insert a array in a JSON object - javascript

I have two arrays called one and two. one contains string values and two int values.
I'm trying:
var messageObject = { 'One': one,
'Two': two};
var serializedJSON = JSON.stringify(messageObject);
var json = JSON.parse(serializedJSON);
alert(json.One);
I'm getting "Undefined", though the array is populated.
They are receiving data from a database, like this:
db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM aluno', [], function(transaction, results) {
len = results.rows.length, i;
for (i = 0; i < results.rows.length; i++) {
one[i] = results.rows.item(i).fieldOne;
two[i] = results.rows.item(i).fieldTwo;
}
}, null);
});
See the code:
http://jsfiddle.net/U4C6r/2/

Edited Answer:
The problem seems to be with the DB-Query-Code. Either the query or the callback get never executed, see: http://jsfiddle.net/U4C6r/11/
Original Answer:
var messageObject = {
'One': one,
'Two': two
};
If you define your keys as strings, you should access them as such:
console.log(json['One']);
If you'd like to have them as properties on the object, you should do:
var messageObject = {
One: one,
Two: two
};
Then you could access the data in a chaining fashion, like you want to:
console.log(json.One);
You should also see the difference here and in your IDE
by the specific Syntax-Highlighting - see it? :)

EDIT to updated:
put breakpoint as you read the values from webSQL and check the structure of object you get within loop inspect this obj results.rows.item(i)
Also change your script to this. I am assuming you have global var one = []; and var two = []; declared.
var dynamicArrayContainer = { one : [],
two : []};
db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM table', [], function(transaction, results) {
for (var i = 0; i < results.rows.length; i++) {
dynamicArrayContainer .one.push(results.rows.item(i).fieldOne);
dynamicArrayContainer .two.push( results.rows.item(i).fieldTwo);
}
}, null);
});
Try this, put your values directly, as debug exercise
var serializedJSON = JSON.stringify(dynamicArrayContainer);
var json = JSON.parse(serializedJSON);
alert(json.one);

Try this:
var messageObject = { One: 'one',
Two: 'two'};
var serializedJSON = JSON.stringify(messageObject);
var json = JSON.parse(serializedJSON);
alert(json.One);
Good luck
:)
Update: Enquirer edited the query after this reply was posted. This reply pertains to the original query (ie the first part of the current query)

Related

Get payload from String

I have this String:
['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
I want to get the keys 'TEST1-560' which is always fist and "car" value.
Do you know how I can implement this?
This is a very, very scuffed code, but it should work for your purpose if you have a string and you want to go through it. This can definitely be shortened and optimized, but assuming you have the same structure it will be fine.:
// Your data
var z = `['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']`;
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1,dividedVar[ind].split(":")[1].split("}")[0].length-1);
console.log(car)
}
}
console.log(testName);
output:
BLUE
TEST1-560
In a real application, you don't need to log the results, you can simply use the variables testName,car. You can also put this in a function if you want to handle many data, e.g.:
function parseData(z) {
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1, dividedVar[ind].split(":")[1].split("}")[0].length - 1);
}
}
return [testName, car]
}
This will return the variables values in an array you can use
const arr = ['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
const testValue = arr[0];
const carValue = JSON.parse(arr[1]).data[0].car;
console.log(testValue);
console.log('-----------');
console.log(carValue);
If your structure is always the same, your data can be extracted like above.

Getting the lengh of an JSON array

I am having a json file. I can get the data in the json file using
$.getJSON.json("mock/Insight72.json", function (jsondata) {
response = jsondata.Data1;
response2 = jsondata.Data2;
});
But I want to find the length of the Data1 and Data2. What should I do?
Here`s the JSON data(Only the Fruit Part)..
],
"Data1": {
"kitchen selectives": [{
"displayColor": "#DC143C",
"numProducts": 1,
"averagePrice": 25.99,
}],
"aroma": [{
"displayColor": "#991F1F",
"numProducts": 1,
"averagePrice": 60.25,
}, {
"displayColor": "#DC143C",
"numProducts": 1,
"averagePrice": 46.19,
}, ............
As Data1 appears to be an Object ({...}), it'll only have a length if one was explicitly given as another key/value:
{
"aroma": [],
"length": 2
}
However, if you'd like to know the number of keys/properties it has, you can use Object.keys():
var keyCountData1 = Object.keys(jsondata.Data1).length;
You can also retrieve the length of any Array ([...]) within Data1, such as "aroma":
var aromas = jsondata.Data1.aroma.length;
Or, if you want to know the length of the Object as JSON:
var dataLength = JSON.stringify(jsondata.Data1).length;
Beyond that, however, you'll have to clarify exactly what "length" you're hoping for.
To find out how many elements are in the response object, you can do something like:
var length = 0;
for (var key in response) {
response.hasOwnProperty(key) && ++length;
}
If you want to find out the total length of all the arrays under it, you can do something like:
var length = 0;
for (var key in response) {
response.hasOwnProperty(key) && length += response[key].length;
}
You can use two different approaches
This one is not compatible with IE7 and 8. Look here as well.
var length = Object.keys(response).length;
var length2 = Object.keys(response2).length;
This one will itterate through json and return length:
function getJSONLegth(response) {
var count = 0;
for (var k in response) {
count++;
}
return count;
}
var length = getJSONLegth(response);
var length2 = getJSONLegth(response2);
Did it help you?

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

iterating over JSON in javascript to put into select options

I keep having issues iterating over some JSON to put in select options
(btw, ignore the actual values for "label", those are garbage atm).
Here is an example that my php is passing into this:
[{"value":"1","label":"04-22-12"},{"value":"4","label":"04\/04\/12"}]
I am currently trying this loop:
*note, dateSelect is defined somewhere else
for (res in JSON.parse(request.responseText)) {
var date = document.createElement("option");
date.value = res.value;
date.text = res.label;
dateSelect.add(date, null);
}
However, it is adding "undefined" into my options...
How do I get it so each value and corresponding label is put in there correctly?
You have an Array, so don't for-in.
In your code, res is the property name (the index of the Array in this case) in the form of a string, so the properties you're looking for aren't going to be defined on the string.
Do it like this...
for (var i = 0, parsed = JSON.parse(request.responseText); i < parsed.length; i++) {
var res = parsed[i];
var date = document.createElement("option");
date.value = res.value;
date.text = res.label;
dateSelect.add(date, null);
}

How to separate the values from two dimension array in js?

jQuery.get("ChkNewRspLive.php?lastmsgID=" + n, function(newitems){
//some code to separate values of 2d array.
$('#div1').append(msgid);
$('#div2').append(rspid);
});
Let's say the value of newitems is [["320","23"],["310","26"]]
I want to assign "320" and "310" to var msgid.
I want to assign "23" and "26" to var rspid.
How to do that?
I tried to display newitems and the output is "Array". I tried to display newitems[0] and the output is blank.
If I redeclare var newitems = [["320","23"],["310","26"]]; it works. So I guess the variable newitems from jQuery.get is something wrong. Is it I cannot pass the array from other page to current page through jQuery directly?
Regarding the array on other page, if echo json_encode($Arraytest); the output is [["320","23"],["310","26"]] but if echo $Arraytest; the output is Array. How do I pass the array from other page to currently page by jQuery.get?
I don't totally understand the question but I'm going to assume you want the values in an array, as two values can't be stored in one (scalar) variable simultaneously.
jQuery.get("ChkNewRspLive.php?lastmsgID=" + n, function(newitems){
//some code to separate values of 2d array.
var msgid = [],
rspid = [];
for( i = 0 ; i < newitems.length ; i++){
msgid[msgid.length] = newitems[i][0];
rspid[rspid.length] = newitems[i][1];
}
//msgid now contains ["320","310"]
//rspid now contains ["23","26"]
});
Bear in mind those are in the function scope. If you want to use them outside of that scope instantiate them outside. see: closure
You can use pluck from underscore.js: http://documentcloud.github.com/underscore/#pluck
var msgid = _(newitems).pluck(0)
var rspid = _(newitems).pluck(1)
Try this:
function getArrayDimension(arr, dim) {
var res = [];
for(var i = 0; i < arr.length; i++) {
res.push(arr[i][dim]);
}
return res;
}
var newitems = [["320","23"],["310","26"]];
var msgid = getArrayDimension(newitems, 0);
var rspid = getArrayDimension(newitems, 1);
msgid and rspid are arrays holding the 'nth' dimention.
Tnx

Categories