Parsing JSON data with jQuery - javascript

So I'm using Yahoo's API to translate coordinates to a zip code. The JSON it returns is this:
{
"ResultSet": {
"version": "1.0",
"Error": 0,
"ErrorMessage": "No error",
"Locale": "us_US",
"Quality": 99,
"Found": 1,
"Results": [{
....
}]
What I am doing is:
$.getJSON("http://where.yahooapis.com/geocode?q=" + lat + ",+" + lon + "&gflags=R&flags=J", function(data){
console.log(data.ResultSet.Results.postal);
});
What I listed above obviously doesn't work. My question is: how do I access the data within the Results array?
Thanks

as Results is an array does changing the console log line to the following work?
console.log(data.ResultSet.Results[0].postal)
In which case just loop through the array to get each each element. The code to get JSON looks fine to me, I assume you just missed the array element bit :)

This should work.
$.getJSON("http://where.yahooapis.com/geocode?q=234532,234533&gflags=R&flags=J", function(data){
$.each(data.ResultSet.Results,function(i,item){
console.log(data.ResultSet.Results[i].postal);
});
});
Example : http://jsfiddle.net/ALsHH/11/

The line console.log(data.ResultSet.Results.postal); is attempting to access a property called portal on an object called data.ResultSet.Results however the property doesn't exist as Results is an array of objects.
What you'll probably need to do is iterate of the array something like...
$.getJSON("http://where.yahooapis.com/geocode?q=" + lat + ",+" + lon + "&gflags=R&flags=J", function(data){
for (var i=0; i< data.ResultSet.Results.length; i++) {
console.log("data.ResultSet.Results[i].postal = " + data.ResultSet.Results[i].postal);
});

Related

Convert JSON to HTML: Uncaught TypeError: json.forEach is not a function

I want to convert JSON to HTML to display it on website. I've googled, and this error occurs when when json is a string, and first I need to parse. But when I use JSON.parse, the console says it is already an object (Unexpected token o in JSON at position 1).
$(document).ready(function() {
$("#getMessage").on("click", function() {  
$.getJSON("http://quotes.rest/qod.json", function(json) {
var html = "";
json.forEach(function(val) {
var keys = Object.keys(val);
html += "<div class = 'blabla'>";
keys.forEach(function(key) {
html += "<b>" + key + "</b>: " + val[key] + "<br>";
});
html += "</div><br>";
});
$(".message").html(html);
});
});
});
json is an object, not an array. You can use forEach only on arrays.
As you have done already, you can iterate over the object's keys like this:
Object.keys(json).forEach(function(key) {
var value = json[key];
...
});
In addition to what everyone else said, it appears that the JSON response does not look like you think it does.
var json = {
"success": {
"total": 1
},
"contents": {
"quotes": [{
"quote": "It's not whether you get knocked down, it...s whether you get up.",
"length": "65",
"author": "Vince Lombardi",
"tags": [
"failure",
"inspire",
"learning-from-failure"
],
"category": "inspire",
"date": "2016-08-09",
"title": "Inspiring Quote of the day",
"background": "https://theysaidso.com/img/bgs/man_on_the_mountain.jpg",
"id": "06Qdox8w6U3U1CGlLqRwFAeF"
}]
}
};
var messageEl = document.querySelector('.message');
messageEl.innerText = json.contents.quotes[0].quote;
<div class="message"></div>
$.getJson already transforms a JSON object into a javascript object, so you would not need to parse it again.
However, your problem starts with forEach, which is an Array method, not an Object method, therefor it will not work in your use case.
var jsonKeys = Object.keys(json); jsonKeys.forEach(...) will work, as Object.keys returns an array of Object keys.

How to separate a JSON.stringify result

Related Retrieve two lists, sort and compare values, then display all the results
The question in the related post was how to combine two lists and sort them. The code referenced each item on each list. So, when I got the result, I could manipulate it.
The best solution used console.log(JSON.stringify(result,null,2)); to return the result, nicely combined and sorted.
Trouble for me is being able to translate that back into something I can work with. I can get the result into a variable and display it on the page, but it's the raw output : [ { "Title": "apple", "Type": "rome", "State": null }, ...
Have tried 'JSON.parse(result);' where result is the variable that is used to handle the combination and sorting of the two lists. All that gives is an invalid character error on the line. Also looked at the 'replace' option. That just confused me, tmi. Tried setting a variable directly on the result (so those who know are laughing) 'var foo = result;' That returns object, object.
The desired end result would be to end up with each item separate so I can put them in a table (or a list) on my html page with blanks in any column where there is no data.
I know there has to be a simple, easy way to do this without 200 lines of transformation code. But I can't find a clear example. Everything I'm seeing is for +experts or uses a super simple array that's typed into the code.
Is there a way to attach something like this (from my original) to the result instead of using JSON.stringify? What other step(s) am I missing in being able to extract the fields from JSON.stringify using JSON.parse?
}).success(function (data) {
var title = '';
var type = '';
$.each(data.d.results,
function (key, value) {
title += "Title: " + value.Title + "<br/>";
type += "Type: " + value.Type + "<br/>";
});
$("#tdtitle").html(title);
$("#tdtype").html(type);
Terry, you wrote: "All that gives is an invalid character error on the line"? Then result is not a valid json. Test it here: http://jsonlint.com/, fix it, then try again.
var data = {
d:{
results: [
{ "Title": "apple", "Type": "rome", "State": null },
{ "Title": "grape", "Type": "fruit", "State": null }
]
}
};
var title = '';
var type = '';
$.each(data.d.results, function (index, value) {
title += "Title: " + value.Title + "<br/>";
type += "Type: " + value.Type + "<br/>";
});
alert(title + type);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Getting json data from a nested array

I'm having a bit of trouble wrapping my head around some JSON stuff. Namely, I'm trying to retrieve a string from a json response received from the google translate api i'm querying.
var translator = function () {
for (var i = 0; i < result.length; i++)
{
//Construct URI
var source =
'https://www.googleapis.com/language/translate/v2?' +
'key=MY-API-KEY-REMOVED-ON-PURPOSE&' +
'source=en&' +
'target=fr&' +
'q=' +
result[i][1]; //looping over an array, no problem there
//Receive response from server
var to_Translate =new XMLHttpRequest();
to_Translate.open("GET",source,false);
to_Translate.send();
var translated = to_Translate.responseText;
JSON.parse(translated);
translated = translated.data.translations[0].translatedText;
console.log(translated);
}
};
translator();
Where
console.log(translated);
yields
{
"data": {
"translations": [
{
"translatedText": "some stuff that's been translated"
}
]
}
}
My question is: how can i access the value of translatedText? I've tried:
translated.data.translations[0].translatedText;
But it doesn't seem to work. When I console.log this i get
Uncaught TypeError: Cannot read property 'translations' of undefined
translator
(anonymous function)
Let me know what you guys think!
That is just text you have to parse it with
JSON.parse(translated)
so you could access it with, for example, translated.data
UPDATE
The error you are getting means that translated.data is undefined, you have to assign the parse to a variable, otherwise it will never work, it doesn't modify it in place
var translated = JSON.parse(to_Translate.responseText);
Yes, Use
translated.data.translations[0].translatedText;
Hope it will work fine.
So close!
translated.data.translations[0].translatedText;
translations is an array of objects, and you want the translatedText property of the first element in the array.
UPDATE:
Just to confirm the output of to_Translate.responseText is a string containing:
{
"data": {
"translations": [
{
"translatedText": "some stuff that's been translated"
}
]
}
}
So you should be able to do:
var translated = to_Translate.responseText,
parsed = JSON.parse(translated),
text = parsed.data.translations[0].translatedText;
console.log(text);

displaying json data in javascript not working

I have created a var and passed JSON data(comma seperated values) to it, but when I want to display json data - it only returns null. Here's the code:
<script type="text/javascript">
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"}
];
document.write(data1);
</script>
You can either do it like this:
var data1 = [{order:"145",country:"Dubai",employee:"permanent",customer:"self"} ];
data1.forEach(function(data){
document.write(data.order);
document.write(data.country);
document.write(data.employee);
document.write(data.customer);
});
or you can do it like this
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"}
];
$.each(data1[0], function(key, value){
document.write(key + " " + value);
});
Either way, storing just one object in the list makes this answer a bit redundant unless I show you how to loop over multiple objects.
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"},
{order:"212",country:"Abu-Dhabi",employee:"permanent",customer:"Tom"}
];
data1.forEach(function(data){
$.each(data, function(key, value){
document.write(key+" "+value);
});
});
I'm using a mix of jQuery here aswell, which might not be optimal but atleast it serves to show that there are multiple ways to accomplishing what you need.
Also, the forEach() method on arrays is a MDN developed method so it might not be crossbrowser compliant, just a heads up!
If you want pure JS this is one of the ways to go
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"},
{order:"212",country:"Abu-Dhabi",employee:"permanent",customer:"Tom"}
];
for(json in data1){
for(objs in data1[json]){
document.write(objs + " : " + data1[json][objs]);
}
}
For simple and quick printing of JSON, one can do something like below and pretty much same goes for objects as well;
var json = {
"title" : "something",
"status" : true,
"socialMedia": [{
"facebook": 'http://facebook.com/something'
}, {
"twitter": 'http://twitter.com/something'
}, {
"flickr": 'http://flickr.com/something'
}, {
"youtube": 'http://youtube.com/something'
}]
};
and now to print on screen, a simple for in loop is enough, but please not e, it won't print array instead will print [object Object]. for simplicity of answer, i won't go in deep to print arrays key and value in screen.
Hope that this will be usefull for someone. Cheers!
for(var i in json) {
document.writeln('<strong>' + i + '</strong>' +json[i] + '<br>');
console.log(i + ' ' + json[i])
}

getJSON to fetch data from this json array

This is a sample json array from my code. How can i use getJSON to fetch data from this array.
"Restoration": [
{
"Easy": {
"value": "1",
"info": "This is Easy."
},
"Medium": {
"value": ".75",
"info": "This is Medium."
},
"Difficult": {
"value": ".5",
"info": "This is Difficult."
}
}
]
using jQuery jQuery.getJSON():
$.getJSON('ajax/test.json', function(data) {
console.log(data); //see your data ( works in Chrome / FF with firebug)
console.log(data["Restoration"][0]["easy"]["value"]) //should output 1
});
This is an alternative to use "jQuery.getJSON()" because sometimes we don't have a "domain/file.json" or somewhere to do the $get or we don't want to use jQuery
for this simple process.
This method parses json from string.
You can do it with simple javascript like this:
//json string for testing
var jsonstr = '{"id":"743222825", "name":"Oscar Jara"}';
//parse json
var data = JSON.parse(jsonstr);
//print in console
console.log("My name is: " + data.name + " and my id is: " + data.id);
Hope this helps.
Regards.
This might help you.
http://underscorejs.org/#keys
var list=_.Keys(data["Restoration"][0]);

Categories

Resources