I am trying to loop through some data received from a page, and if the price of the item (it's in the data) is under a certain amount I want to make an alert. But I was wondering how I can successfully loop through all the data from this site.
http://www.roblox.com/catalog/json?browse.aspx?Subcategory=2&Keyword=&CurrencyType=0&pxMin=0&pxMax=0&SortType=2&SortAggregation=0&SortCurrency=0&PageNumber=1&LegendExpanded=true&Category=2
I think I can do the part of the alerts and such if I can just figure out the looping.
setTimeout(function(){
var myjson;
var page = 1;
$.getJSON("http://www.roblox.com/catalog/json?browse.aspx?Subcategory=2&Keyword=&CurrencyType=0&pxMin=0&pxMax=0&SortType=2&SortAggregation=0&SortCurrency=0&PageNumber="+page+"&LegendExpanded=true&Category=2", function(json){
myjson = json;
alert(myjson[0].Description);
});
//var new_json = JSON.parse(myjson);
}, 2000);
Try this
$.getJSON("http://www.roblox.com/catalog/json?browse.aspx?Subcategory=2&Keyword=&CurrencyType=0&pxMin=0&pxMax=0&SortType=2&SortAggregation=0&SortCurrency=0&PageNumber="+page+"&LegendExpanded=true&Category=2", function(json){
$.each(json, function(i, field){
console.log(field["Description"]);
});
});
You need to parse the JSON string to an object.
var obj = jQuery.parseJSON( '{ "foo": "bar" }' );
alert( obj.foo );
http://jsfiddle.net/w2xcT/
Related
I am a beginner in Javascript. I hope to get some help.
I built a local server using MAMP, and all my files are local. I want to read a value from a json file. This json file(data.json) has only one item {"type":2}, and I only want to use the value(2 in this case). But the value of "type" changes, so Javascript should read it constantly and maybe save it into a var in Javascript.
Can I listen for changes to that file so that I can be sure I always have the most up to date value for type?
I am still not familiar with Javascript. I would really appreciate it if you could give me some specific codes or examples.
//Either
var json = {test:"test"};
console.log(json);
//Access JSON
console.log(json.test);
//Or
$.getJSON( "test.json", function( data ) {
//Assign the json to your JSON variable
json = data;
});
console.log(json);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
JSON can come from anywhere, inbuilt into jquery is parseJSON which will return the json input string as a javascript object.
http://api.jquery.com/jquery.parsejson/
var obj = $.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );
where the json can come from anywhere.. an ajax call or where ever else.
$.ajax({
url:'some url',
data: someobject,
type: 'get',
success: function( responseFromServer ){
var obj = $.parseJSON( responseFromServer );
alert( obj.name === "John" );
}
});
this is my first question here! New to using Ajax, and have hit an issue that maybe someone could catch what I am doing wrong.
var featuredList;
$.ajax({
url: "myurl",
type: 'GET',
success: function(result){
featuredList = JSON.stringify(result);
alert(result);
$.each( result, function( key, value ) {
alert('not working');
});
},
error: function(){alert('error');}
});
I have gone this path before with no issues, this time around I cannot get inside the loop. The alert(result) is returning my data just fine.
Thanks!
Hi,
Hope this might help you to process JSON data received from AJAX request, try below code:
jQuery.ajax({
url:'myurl',
dataType: "json",
data:{
classId:'C001'
},
type: "GET",
success: function(data) {
for (var j=0; j < data.length; j++) {
//syntax to get value for given key
//data[j].yourKey
var userId = data[j].userId;
var name = data[j].name;
var address = data[j].address;
}
}
});
Thanks,
~Chandan
As per your code try doing this:it should work
var data = JSON.parse(result);//here result should be json encoded data
$.each( data, function( key, value ) {
alert(value);
});
Use jQuery promises, gives you more semantic and readable code
var featuredList;
$.getJSON("myurl", {"optional": "data"})
.done(function(data){
// successful ajax query
$.each( data, function( key, value ) {
// do whatever you want with your iterated data.
});
});
.fail(function(){
// catch errors on ajax query
});
I do it this way
$.getJSON('url',
function(dataList) { // on server side I do the json_encode of the response data
if(dataList !== null) {
$.each(dataList, function(index, objList ) {
// rest of code here
});
}
});
Hope this works for you as well.
function getArray(){
return $.getJSON('url');
}
var gdata = [];
getArray().then(function(json) {
$.each(json, function(key, val) {
gdata[key] = val ;
});
console.log(gdata);
I had the Same Problem It took 2 days to got the solution.
You have to resolve the promise and return the json object to access the value.
You could easily do this using the open source project http://www.jinqJs.com
/* For Async Call */
var result = null;
jinqJs().from('http://.....', function(self){
result = self.select();
});
/* For Sync Call */
var result = jinqJs().from('http://....').select();
You can also use $.Json to get your solution , here is an example
$.getJSON('questions.json', function (data) {
$.each(data,function(index,item){
console.log(item.yourItem); // here you can get your data
}
}
You can use or print Index if you want it. Its show the data index.
Hope it may help you, I am exactly not sure its your requirement or not, But i have tried my best to solve it.
This will work as the result from ajax call is a string.
$.each($.parseJSON(result), function( key, value ) {
alert('This will work');
});
I Have a jQuery Post to a PHP page with generates a JSON Response. It successfully generates JSON because I have it display the whole response. But on the .each I cannot get it to alert. Any Ideas Appreciated. Thank You. The JSON looks like:
[{"Part_Field":"Part_Note:3","Part_Value":"ValueofPart"},{"Part_Field":"Ft_In:3","Part_Value":"12"}, ...
jQuery:
$.post('/scripts/update_detail.php' , field_id + "=" + value, function(data){
var d = document.getElementById("displayjson");
d.innerHTML = data;
$.each( data, function( key, value ) {
alert( value.Part_Field );
});
});
You forgot the string },"json"); in the end.
The corrected code should be:
$.post('/scripts/update_detail.php' , field_id + "=" + value, function(data){
var d = document.getElementById("displayjson");
d.innerHTML = data;
$.each( data, function( key, value ) {
alert( value.Part_Field );
});
},"json"); // Here, you need to tell jQuery that whatever response
// we are getting from server is a JSON string, in your case,
//it was considering it as a string.
A site that I'm using contains a JavaScript file, inside the file it contains a code with JSON and goes like this:
$.getJSON(API_URL + getSubdomain() + "/values");
The data file contains the code:
{"has_clicked_all":false,"has_clicked_already":false,"buttons":
[{"id":3922,"name":"button3992","has_clicked":false},
{"id":4613,"name":"button4613","has_clicked":false},
{"id":4339,"name":"button4339","has_clicked":false},
{"id":4340,"name":"button4340","has_clicked":false},
{"id":4341,"name":"button4341","has_clicked":false},
{"id":4622,"name":"button4622","has_clicked":false},
{"id":4623,"name":"button4623","has_clicked":false},
{"id":4828,"name":"button4828","has_clicked":false},
{"id":4829,"name":"button4829","has_clicked":false},
{"id":4861,"name":"button4861","has_clicked":false}]}
What I'm wanting to do is change all the value's to true without clicking on all of the buttons. I've tried doing a lot of research and spent 4 hours figuring out how I could do this and me being very new to all this just leaves me stuck...
I just need someone to give me a hand it would be greatly appreciated! Thankyou
Parse the json , modify the data , then re-encode to json
javascript:
var data = JSON.parse(json);
for(i = 0; i < data.buttons.length; i++){
data.buttons[i].has_clicked = true;
}
data.has_clicked_all = true;
data = JSON.stringify(data);
console.log(data);
demo
jQuery :
(function() {
$.getJSON(API_URL + getSubdomain() + "/values", function(data) {
data.has_clicked_all = true;
$.each( data.buttons, function( i, item) {
data.buttons[i].has_clicked = true;
});
data = JSON.stringify(data);
alert(data);
});
})();
I have a places.php file on my server that returns the following json:
{"places":[{"poi_id":"1","poi_latitude":"53.9606","poi_longitude":"27.6103","poi_title":"Shop1","poi_category":"Shopping","poi_subcategory":"Grocery Store","poi_address":"Street 1, 1","poi_phone":null,"poi_website":null},{"poi_id":"2","poi_latitude":"53.9644","poi_longitude":"27.6228","poi_title":"Shop2","poi_category":"Shopping","poi_subcategory":"Grocery Store","poi_address":"Street 2","poi_phone":null,"poi_website":null}]}
In my javascript I use the following piece of code:
$(document).ready(function() {
var url="places.php";
$.getJSON(url,function(data){
$.each(data.places, function(i,place){
var new1 = place.poi_id;
alert(new1);
});
});
});
However the message box with the poi_id doesn't pop up. What am I doing wrong?
How about like this.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
// data source
var jsonStr = '{"places":[{"poi_id":"1","poi_latitude":"53.9606","poi_longitude":"27.6103","poi_title":"Shop1","poi_category":"Shopping","poi_subcategory":"Grocery Store","poi_address":"Street 1, 1","poi_phone":null,"poi_website":null},{"poi_id":"2","poi_latitude":"53.9644","poi_longitude":"27.6228","poi_title":"Shop2","poi_category":"Shopping","poi_subcategory":"Grocery Store","poi_address":"Street 2","poi_phone":null,"poi_website":null}]}';
// parse json string to object
var jsonObj = JSON.parse(jsonStr);
// usage 1
console.log('iterate - without jQuery');
for (var i = 0; i < jsonObj.places.length; i++)
{
var place = jsonObj.places[i];
console.log(place.poi_id);
}
// usage 2
console.log('iterate - with jQuery');
$(jsonObj.places).each(function(index, place)
{
console.log(place.poi_id);
});
</script>
Output:
How to use this in your code:
$(document).ready(function()
{
$.getJSON("/path/to/places.php", function(data)
{
// data here will be already decoded into json object,
// so... you do this
$(data.places).each(function(index, place)
{
console.log(place.poi_id);
});
});
});
Take a look at the manual also: http://api.jquery.com/jquery.getjson/
Should work, if not leave a comment with an error or reason.
Does this do / get you closer:
for (var property in data)
{
if (data.hasOwnProperty(property))
{
console.log(property);
}
}
Is your php actually generating the JSON? If it's only getting a particular file it may be easier to choose your file using JS and AJAX it. Here's the code I use for php anyway.
function callPHP(dataToSend)
{
$.post( "places.php", dataToSend )
.done(function( phpReturn ) {
console.log( phpReturn );
var data = JSON.parse(phpReturn);
for(var i = 0;i<data.places.length;i++)
console.log(data.places[i].poi_id);
});}
}
Setting places.php file encoding to UTF-8 solved the problem