Hello guys I've web page which have a lot of scripts, I need to get one by it's name. for e.g 'data'. I need to convert data from this script to one string.
Script is the following:
<script>data = [{'Id': '12344567', 'name': 'TestName','Amount': '1066.00', 'NumberTax': '34.00','tranasactionNumber':'139', 'otherInfo': [{'sku': 'ET|Adult','name': 'Test','category': 'Normal','price': '1032.0', 'quantity':'3'}]}];</script>
This data has array with some elements and another array inside.
Using my script I can only get info and create string with String elements from my data, but how can I get elements from inner array?
var json = '[{';
for (var i in data[0]) {
console.log('type of data[0][i] = ' + typeof data[0][i]);
if (typeof data[0][i] === 'string') {
json = json + '\'' + i + '\'' + ': ' + '\'' + data[0][i] + '\', ';
console.log(i);
console.log(data[0][i])
} else {
//Get infro from inner array
}
}
json = json + '}]';
console.log(json);
Try JSON.stringify(data) to convert object to string instead of your function.
To access the object inside the array you can use the following code:
var obj = data[0]['otherInfo'][0];
You can then use the same code you have above to loop over it and append its elements. If I understand correctly that if what you wish to do.
Related
I want to pass all values from Google Sheets to HTML (Google web app) by using Google-Apps-Script doGet() and append in the script to keep as global variable. Faster than html load first then use google.run.script... in my opinion
So getting an object key as a sheet_name and key values as 2D_array data
function getSheetData() {
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets()
var object = {}
for (var i = 0; i < sheets.length; i++) {
object[sheets[i].getName()] = sheets[i].getDataRange().getValues().filter(r => r[0] !== '')
}
return object
}
in function doGet() I'm using append to add the script to the HTML
function doGet() {
var html = HtmlService.createHtmlOutputFromFile('Main')
html.append('<script> var userData = ' + getSheetData() + ' </script>')
return html
}
Still getting <script> var userData = [object Object] </script>
it should be something like <script> var userData = {key1:[2D Array],key2:[2D Array]} </script>
I also tried with string and it works fine. But can we possibly do as an object?
Thank you in advance
html.append(' var userData = ' + getSheetData() + ' ')
When appending html, the script is appending a string. The object returned by getSheetData() is coerced to a string implicitly, when using the + operator. The coercion doesn't produce a full array as string but just as [object Object].
To bypass this, you may use JSON.stringify() server side:
html.append('<script> var userData = ' + JSON.stringify(getSheetData()) + ' </script>')
I am trying to iterate through an array of objects and populate an HTML select element with options whose values are the entire contents of each object. The population is successful, but the objects are turned into strings in the process and I do not know how to turn them back into objects.
Running them through JSON.parse() gives me "Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse." My research suggests that this happens when you use JSON.parse() on something that is already an object, but running typeOf() on the data beforehand reveals that it is a string.
I do not get this error if I instead run the data through JSON.parse(JSON.stringify(data)), but its output remains a string.
Please help me understand what I am misapprehending about JSON.parse(). Thank you.
const selectors = document.getElementsByClassName("ingredientSelector");
const cookButton = document.getElementById("cookButton");
//very large array of ingredient objects
let selectorOptions = "<option value = 'Nothing'>Nothing</option>";
for (let i = 0; i < ingredients.length; i++){
selectorOptions += ("<option value = '" + ingredients[i] + "'>" + ingredients[i].name + "</option>");
}
Array.prototype.forEach.call(selectors,function(selector){
selector.innerHTML = selectorOptions;
});
function cook(ingredients){
console.log("Cooking with ingredients: " + ingredients);
}
cookButton.addEventListener("click", function(){
let ingredients = [];
Array.prototype.forEach.call(selectors,function(selector){
if(selector.value !== 'Nothing'){
console.log(typeof(selector.value))
JSON.parse(selector.value);
let JSONString = JSON.stringify(selector.value);
console.log(typeof(JSONString));
let JSONObject = (JSON.parse(JSONString));
console.log(typeof(JSONObject));
console.log(JSONObject.name);
}
console.log(ingredients);
cook(ingredients);
});
});
The issue is how you're building the value properties for the options you're inserting into each selector. On this line:
selectorOptions += ("<option value = '" + ingredients[i] + "'>" + ingredients[i].name + "</option>");
Your comment says that ingredients is an array of objects, so ingredients[i] will be an object. Concatenating an object to a string will, by default, turn it into [object Object] - and this is what's causing your error. You're ending up with an option that looks something like this, perhaps:
<option value = '[object Object]'>Raw Prime Meat<object>
There's two perfectly valid approaches here. You can either store the ingredient index in the option values, which you can then use to lookup the ingredient from your master array later, or you should use JSON.stringify(ingredients[i]) to turn the object into a JSON.parseable string to make your code work as-is.
So this would work fine:
selectorOptions += ("<option value = '" + JSON.stringify(ingredients[i]) + "'>" + ingredients[i].name + "</option>");
Hi all i am calling a javascript function on WebView in android. I am sending a JSON data which will pass value to html.
My JSON data is in following format i have checked using online tools it is valid.
{"Results":{"Number of Tests":"2","Latency(avg)":"17","Failure":"0%","Latitude":"12° 55' 35.5872'' N","Longitude":"77° 36' 4.16916'' E","Latency(max)":"18","Latency(min)":"17"},"TestStaus":"Passed","Test":"Game Test"}
I am using following code to display parsed result in html using jquery.
var jsonObject = JSON.stringify(vk);
document.write(jsonObject);
$.each($.parseJSON(jsonObject), function(k, v)
{
document.write("<tr><td>" + k + "</td><td>" + v + "</td></tr>");
});
It is giving me output in following manner
Parameter Value
Results [object Object]
TestStatus Passed
Test Game Test
Please help how to read all results. Why it is reading object object.
Just use recursion. You need to be able to handle multidimensional objects. Also, I usually use jquery for DOM or AJAX only. For something like this, you might not need it.
Your Json
var vk = {"Results":{
"Number of Tests":"2",
"Latency(avg)":"17",
"Failure":"0%",
"Latitude":"12° 55' 35.5872'' N",
"Longitude":"77° 36' 4.16916'' E","Latency(max)":"18",
"Latency(min)":"17"
},
"TestStaus":"Passed",
"Test":"Game Test"};
Recursive function
function drawJSON(obj){
for(var key in obj){
if(typeof obj[key] === 'object'){
drawJSON(obj[key]);
continue;
}
document.write("<div><span>" + key + "</span><span>" + obj[key] + "</span> </div>");
}
}
drawJSON(vk);
DEMO
The Results is object so it is showing as [object object]. You can do this by:
function printEach(jsonObject) {
$.each(jsonObject, function(k, v)
{
if(typeof v === 'object') {
printEach(v);
} else {
console.log("<tr><td>" + k + "</td><td>" + v + "</td></tr>");
}
});
}
var vk = {"Results":{"Number of Tests":"2","Latency(avg)":"17","Failure":"0%","Latitude":"12° 55' 35.5872'' N","Longitude":"77° 36' 4.16916'' E","Latency(max)":"18","Latency(min)":"17"},"TestStaus":"Passed","Test":"Game Test"};
var jsonObject = JSON.stringify(vk);
printEach($.parseJSON(jsonObject));
You can see the fiddle http://jsfiddle.net/58grs/1/
This question already has answers here:
JSON dot notation to string
(3 answers)
Closed 9 years ago.
I am converting JSON data into a list structure, and I want to save the "AAA.BBB[0].CCC.DDD[5].EEE" format as the id so when a user modifies the content of that list item it modifies the JSON data associated with that location.
For Example AAA.BBB[0].CCC.DDD[5].EEE = 123
123 is a list item but I want the id to be saved as "AAA.BBB[0].CCC.DDD[5].EEE"
Would there be a better way to save the location in the id?
*Edit:
Sample Code:
JSON DATA: {"AAA":{"AAB":"Value1","AAC":"Value2","AAD":1,"AAE":"Value3","AAF":"{"ABC": "Value4"}}}
Soo the id for list item "Value4" would be AAA.AAF.ABC
function nodeIT(obj,output){
for (var x in obj){
if(!(obj[x] instanceof Object)){
//var str =JSON.stringify(obj); // Where im stuck!
output +="<li id='"+str+x +"'>";
output += (x + "=" + obj[x] + "<br />");
output +="</li>";
}
else if((obj[x] instanceof Object)){
var obj1 = obj[x];
output+="<li>" +x + "<ul>";
output=nodeIT(obj1,output);
}
}
output += "</ul></li>";
return output;
}
Instead of using the ID attribute and being forced to use a single string, you could take advantage of jQuery's .data() method, which lets you associate javascript objects with html elements.
So you do something like this when you're building the list elements:
var liElement = $('<li />')
.text(x + "=" + obj[x])
.data({
container: obj,
key: x
});
And then access the data later like this (where this refers to an li):
var container = $(this).data('container');
var key = $(this).data('key');
var value = container[key];
// .. modify value
container[key] = value;
Please see a full example here: http://jsfiddle.net/h38Ec/
I was trying to return a string from my server which would be parsed into a javascript object. I keep getting an error though when it comes to the parsing process. I didnt know why. Maybe you know something that i do not.
My string looks like this:
{{"fname":"bob","lname":"jones"},{...}}
What i was trying to do is something like
var item = JSON.parse(myString);
It should be making item, an array of names so i could do something like:
for(var i = 0; i < item.length; i++){
alert(item[i].fname + " " + item[i].lname);
}
Is there something i am doing wrong? The above was a sample, but below is actually code snippet:
while (reader.Read())
{
if (reader["rt_id"] != DBNull.Value && reader["rt_name"] != DBNull.Value)
{
t = #"{""pValue"":""{ReportType},"+reader["rt_id"]+#""",""pText"":"""+reader["rt_name"]+#"""}";
returnContentsArray.Add(t);
}
}
returnContents = "{" + String.Join(",",returnContentsArray.ToArray()) + "}";
return returnContents;
On Client:
var item = JSON.parse(result);
That string is not valid JSON. {} represents an object, which needs to have keys. It seems you want an array, use [] instead.
returnContents = "[" + String.Join(",",returnContentsArray.ToArray()) + "]";
You need to use correct JSON format. It looks like the format you should be using is
[{"fname":"bob","lname":"jones"},{...}]
Which would return an array of objects. Just make user you can validate the JSON in JSONLint of similar before trying to change up your javascript code.