My web service returned a JSON Array (ie. [{"key":"value"}, {"key":"value2"}]). In the array there are two items as you can see, which are separated with comma. I want to know how can I access the second item, and get the value of "key" for the second item.
I've tried:
var a = msg.d[1].key
With no success of course.
This is the returned string:
"[{"Code":"000000","Name":"Black","Id":9},{"Code":"BF2C2C","Name":"Red","Id":11}]"
The string was extracted using FireBug after watching the msg.d.
Need your help in solving this.
msg[1].key
Assuming that the name of that array is msg. I'm not sure what you are using .d for.
If msg.d is a string representing an array, use JSON.parse.
JSON.parse(msg.d)[1].key
You can replace key with the key you are wanting, e.g. Code, Name, Id, etc.
This works as expected for me.
var msg = [{"key":"value"}, {"key":"value2"}];
var a = msg[1].key;
What is msg in the example above? Need more info to help.
If msg.d is a string then you have to eval (uggh) or parse it before applying the array subscript.
Related
How do I access the value stored in the description property using javascript?
As seen in the image below (a screenshot from the browser console), the stored value is [STK_CB - ] Request Cancelled by user
In the browser console, I have tried console.log(responseMan.payload["0"].jsonPayload.description); which shows undefined. Where am I going wrong?
Looking forward to your help.
The value of jsonPayload is a string, not an object -- notice the double quotes around it. And the name of the property implies that it's JSON. You need to call JSON.parse() to convert it to an object.
var payload = JSON.parse(responseMan.payload[0].jsonPayload);
console.log(payload.description);
just remove " from index and do it like:
u also have to cast the json first
const jsonStr = responseMan.payload[0].jsonPayload;
const data = JSON.parse(jsonStr);
console.log(data.description);
The problem is in your json. Because you are trying to access responseMan.payload ["0"]. JsonPayload up there is a correct element in the json. But the description is a string value in responseMan.payload ["0"]. JsonPayload, therefore, must format the contents of responseMan.payload ["0"]. JsonPayload on a json object. Example var obj = JSON.parse (responseMan.payload ["0"]. JsonPayload); and so
description will be a json object
OR
You can fix that json in your backend and send that section as a json and not as a string
I have an array value which is coming from database as an string. I need to convert it into an array. When I check my value in console I can see value as
"[["COL1","COL2","COL3"],["COL4","space,"COL5"]]"
In order to perform my operations I need it to be in below structure
[["COL1","COL2","COL3"],["COL4","space,"COL5"]]
I have already tried JSON.parse() and parseJSON
Expected Result :
[["COL1","COL2","COL3"],["COL4","space,"COL5"]]
Actual Result :
"[["COL1","COL2","COL3"],["COL4","space,"COL5"]]"
You need to remove the outer quotes from your string, then pass the value to JSON.parse() to get the array.
Also, you have to quote each item correctly, "space should be "space".
You can sanitize the string with String.prototype.replace() (assuming the quoting of space has been fixed in the DB):
const data = '"[["COL1","COL2","COL3"],["COL4","space","COL5"]]"';
const dataSanitized = data.replace(/^"|"$/g,"");
console.log(JSON.parse(dataSanitized));
I would suggest you do parse
JSON.parse('[["COL1","COL2","COL3"],["COL4","space","COL5"]]')
i would not suggest eval as i just read an article about "how eval is evil"
https://javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval/
I'm trying to generate a google form that has a few hundred options in a drop down.
I have all the name values in a single cell formatted as follows:
'user1','user2','user3'
It is set as in the code as follows:
var studentNames = SpreadsheetApp.openById('REDACTED').getSheetByName('Student List').getRange(3,3).getValues();
When I use this variable as shown below it treats it all as a singe value instead of an array.
.setChoiceValues([studentNames])
Any help in where to go from here?
is it a string of words with single quotes and a comma to separate them? if so, you can just do a split on the comma
var s = data
var arr = s.split(",");
and now you will have an array of strings. not sure if this answers your question.
Thanks everyone for getting me pointed in the right direction.
Turns out split was just part of the answer, I had to turn it into a string first.
.toString().split(",");
getValues() returns an object, so you need to interact with it to get the string of values for your array.
Given you are selecting just one cell and so don't need to iterate through the object, try something like this:
var studentNamesObj = SpreadsheetApp.openById('REDACTED').getSheetByName('Student List').getRange(3,3).getValues();
var studentNames = studentNamesObj[0][0].split(",");
I´m having a problem with a javascript function.
The idea is read the content of a file with javascript. Everything is working ok, I can see the content of the file, just now I want to organize the content.
And what I meant with organize is:
My file have a lot of strings, for example: tel#01234567#tel tel#01456789#tel dept#level1#dept dept#level4#dept.....
And everything is a line of strings, and at the end is that all what I see...
My goal is, when I read the file, at the end it have to show something like this:
Tel: 01234567
01456789
Dept: Level1
Level2
There is a way to have something like that?
function loaded(evt)
{
// Obtain the read file data
var fileString = evt.target.result;
document.getElementById('output').innerHTML = fileString;
}
So basically your file has attributes and data for the respective attribute surrounded by the attribute name + #?
The easiest thing would be to have the file in a common format for data, e.q. JSON. Then you could just use the attributes from the object you get by JSON.parse();
However, if you cannot change the file structure you will have to programm something that splits your string into the desired parts and creates an object out of the attributes to work with.
For the string you presented you could do one string.split(" ") to get every attribute singled out, resulting in an array like this:
Array [ "tel#01234567#tel", "tel#01456789#tel", "dept#level1#dept", "dept#level4#dept" ]
Afterwards you can iterate over the array and string.split("#") again for each element which gives you this:
array[0].split("#");
Array [ "tel", "01234567", "tel" ]
Then you can use the first index of the array as attribute name and the second one as its data. You could put that into an object and afterwards refer from the attribute straight to the data:
var string = "tel#01234567#tel tel#01456789#tel dept#level1#dept dept#level4#dept";
var array = string.split(" ");
var dataObject = {};
for(var i in array){
var element = array[i].split("#");
if(dataObject.hasOwnProperty(element[0])){
dataObject[element[0]].push(element[1]);
}else{
dataObject[element[0]] = [element[1]];
}
}
In the end you have an object that has all the attributes as its properties and the corresponding data stored in an array for each property. With that you should be able to work right? :)
When you read the file in you could use JS split to separate the content based on the delimiters.
Check it out here: http://www.w3schools.com/jsref/jsref_split.asp
I have json returned from Database.I want to pick only one object Value and show it in the textbox. Here is my json.
[{
"ErrorMessage":"",
"ID":294,
"ExpenseID":0,
"EffectiveDate":"/Date(1262284200000)/",
"FormattedEffectiveDate":"01-01-2010",
"Perunit":null,
"VATRate":17.5,
"ChangedByID":1,
"ChangedByName":"superuser, superuser",
"Expense":null,
"ErrorSummary":null,
"ErrorList":[]
}]
I have Tried
var Jsoninvoice = JSON.stringify(data)
alert(Jsoninvoice.VATRate) and also alert(data.VATRate)
Thank you In advance.
You have an array containing 1 object. stringify turns this object into a string - you need it parsed so you can use it.
(I'm not sure if the object is parsed already, so to cover all bases, we'll parse it)
var Jsoninvoice = JSON.parse(data);
alert(Jsoninvoice[0].VATRate);
You have to specify the arrays index before you can access the properties.
It is already json object and stringify is not needed as #tymJV said you need to parse it if it is returned as string, just you need to access array item, as it is an array:
alert(data[0].VATRate)
SEE FIDDLE
You could use $.parseJSON(YOURJSON), and then use the keys to pull the data. Since it's in an array, you'll have to use [0] to pull the first item in the array (ie: your data).
Example
$(document).ready(function(){
var j ='[{"ErrorMessage":"","ID":294,"ExpenseID":0,"EffectiveDate":"/Date(1262284200000)/","FormattedEffectiveDate":"01-01-2010","Perunit":null,"VATRate":17.5,"ChangedByID":1,"ChangedByName":"superuser, superuser","Expense":null,"ErrorSummary":null,"ErrorList":[]}]';
var json = $.parseJSON(j);
alert("VATRate: "+json[0].VATRate);
});
Fiddle for reference