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/
Related
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>");
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.
I have an object 'res' and it holds a field:
res.headers=new object();
im using this field as a map which holds key and value meaning:
res.headers['key']='value';
is there any way to get the content of this map by iterating it without knowing the key?
thank you!
for(var key in res.headers) {
if(res.headers.hasOwnProperty(key)) {
console.log(key + " -> " + res.headers[key]);
}
}
or with Object.keys():
for(var key in Object.keys(res.headers)) {
console.log(key + " -> " + res.headers[key]);
}
Easiest thing to do is use a javascript library, like underscore for example, then use someting like:
arr = _.values(res.headers)
arr[0] // value of first element
I've declared myself a JavaScript object called "breakdown".
I've then borrowed a function which I found on the jQuery extend() documentation, which works perfectly well on a different page, but identical setup - rewards object instead of breakdown.
breakdown = {};
breakdown.printObj = function(obj) {
var arr = [];
$.each(obj, function(key, val) {
var next = key + ": ";
next += $.isPlainObject(val) ? printObj(val) : val;
arr.push( next );
});
return "{ " + arr.join(", ") + " }";
}
I'm then trying to use it as I have on the other page to see what is in my "categories" array:
breakdown.getPointsBreakdown = function(categories, transactions) {
alert( breakdown.printObj(categories) );
If I "typeof" that alert instead, it displays "object". If I alert "categories[1].Title", it displays "Good Behaviour", so the array is being passed to the categories variable in this function correctly.
However, when I use "breakdown.printObj", I get the following error in FireBug:
ReferenceError { message="printObj is not defined", fileName="https://frog.ashingtonh...7fa8452ccb3e94ba89e487a", more...}
I don't understand how!
Change
next += $.isPlainObject(val) ? printObj(val) : val;
to:
next += $.isPlainObject(val) ? breakdown.printObj(val) : val;
You should probably have breakdown.printObj(val) rather than just printObj(val) in line 6.
Change
breakdown.printObj = function(obj) {
// snip...
};
to
breakdown.printObj = function printObj(obj) {
// snip...
};
so that you can call it recursively.
This is called named function expression.
Hey guys! First of all, I know this kind of stuff is quite shitty, but that's the way I visualize achieving my goal.
Here is the deal: I have a JSon object that contains an array, but unfortunately, I have to iterate through the list of one JSon object, and then iterate throught that array I mencioned before. The JSon object look as follows (it is in portuguese, but you guys can understand it):
{"produtos":[{"Key":"DERIVADOS DE FERRO","Value":217816909},{"Key":"MADEIRAS,
SUAS MANUFATURAS E MOBILIÁRIO MÉDICO
CIRÚRGICO","Value":117812290},{"Key":"CELULOSE,
PAPEL E SUAS
OBRAS","Value":100086937},{"Key":"CARNE
SUÍNA","Value":81738783},{"Key":"CARNE
BOVINA","Value":74894768},{"Key":"CARNE DE
AVES","Value":65292433},{"Key":"Outros","Value":444520811}],"ano":2005,"tipo":1}
Produtos is the array I mentioned, and I have two other values that are important: ano (year) and tipo (type). My code look as follows:
jQuery.getJSON("/webportos/Porto/GraficoComercio?id=" + iddoporto.className + "&ano=2005", null, function (items) {
jQuery.each(items, function (itemNo, item) {
jQuery.each(item.produtos, function (dicNo, dic) {
options.series.push({ name: dic.Key, data: dic.Value});
options.title.text = "Comércio - "+item.ano;
options.yAxis.title.text = "Exportação";
options.tooltip.formatter = function () {
return '<b><u>' + this.series.name + '</u></b><br/><b>' + this.x + '</b>: ' + this.y + ' ';
}
});
});
chart = new Highcharts.Chart(options);
});
This piece of code makes Chrome javascript console to display:
ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js:32 Uncaught TypeError: Cannot read property 'length' of undefined
Can you guys help me out?
Is this because you're trying to use .each() on a non array?
jQuery.each(items, function (itemNo, item) {
From my understanding, jQuery.each(object, callback, args) is only for use on arrays. The first thing it does is make a call to object.length. So unless you have
[{"produtos":[{"Key":"DERIVADOS DE FERRO","Value":217816909},{"Key":"MADEIRAS, SUAS
MANUFATURAS E MOBILIÁRIO MÉDICO CIRÚRGICO","Value":117812290},{"Key":"CELULOSE, PAPEL E SUAS
OBRAS","Value":100086937},{"Key":"CARNE SUÍNA","Value":81738783},{"Key":"CARNE
BOVINA","Value":74894768},{"Key":"CARNE DE AVES","Value":65292433},
{"Key":"Outros","Value":444520811}],"ano":2005,"tipo":1}]
you're gonna get that error.
Additionally, you may take Diodeus's suggestion into consideration. jQuery.each is quite a bit less performant than just using a for to loop through your data.
You don't need jQuery to iterate through JSON data. Use plain old Javascript.
See this question: Display JSON/YAML hierarchy as a tree in HTML?
function renderJSON(obj) {
var keys = []
var retValue = ""
for (var key in obj) {
if(typeof obj[key] == 'object') {
retValue += "<div class='tree'>" + key
retValue += renderJSON(obj[key])
retValue += "</div>"
}
else {
retValue += "<div class='tree'>" + key + " = " + obj[key] + "</div>"
}
keys.push(key)
}
return retValue
}