I have this kind of json string:
{"total":"3","data":[{"id":"4242","title":"Yeah Lets Go!","created":"1274700584","created_formated":"2010-07-24 13:19:24","path":"http:\/\/domain.com\/yeah"}{"id":"4242","title":"Yeah Lets Go!222","created":"1274700584","created_formated":"2010-07-24 13:19:24","path":"http:\/\/domain.com\/yeah222"}{"id":"4242","title":"Yeah Lets Go!333","created":"1274700584","created_formated":"2010-07-24 13:19:24","path":"http:\/\/domain.com\/yeah333"}]}
I would need to parse it to javascript object i believe? And then into html like:
Yeah Lets Go!
<p class="date">Created: 2010-07-24 13:19:24"</p>
but I have no clue how to parse it and so on.
I get that string from this:
$('a.link').click(function() {
var item_id = $(this).attr("href").split('#')[1];
$.get(base_url+'/ajax/get_itema/'+item_id+'/0/3/true', null, function(data, status, xhr) {
$('#contentCell').html(data);
});
Use the JSON.parse function to convert a JSON string into a JS object. Most modern browsers include JSON.parse, but it is also included in json2.js if you need a fallback for older browsers.
Having a div with id result to get the html, something like:
$.getJSON(base_url+'/ajax/get_itema/'+item_id+'/0/3/true', function(data) {
$("#result").empty();
$.each(data.data, function(i, d) {
$("#result").append("<a href='" + d.path + "'>" + d.title + "</a>" +
"<p class='date'>Created: " + d.created_formated + "</p>");
}
});
Since you're using jQuery, take a look at .getJSON()
The way you use .getJSON() is:
jQuery.getJSON( url, [ data ], [ callback(data, textStatus) ] )
url is of course the url you're getting the data from. [ data ] is the stuff you send to the server. [ callback(data, textStatus) ] is a function that handles the data coming back from the server. You can generally leave out the second argument textStatus. The data coming back is understood to be JSON. .getJSON() is shorthand for a .ajax() call that specifies JSON data.
So in your case this would be something like (note that I changed the JSON coming back from the server to response... it's a less confusing nomenclature in your case than using data, since you have a data property in your JSON):
$.getJSON(base_url+'/ajax/get_itema/'+item_id+'/0/3/true', function(response) {
...
});
So, to recover things from response we simply access them using dot and square bracket notation. To get the first set of data:
response.data[0].title \\ <== "Yeah Lets Go!"
response.data[0].path \\ <== "http://domain.com/yeah"
The above looks in response which is our JSON object. Then it looks at the first data elment (there are 3) and pick the title in the first line and the path in the second.
Since you're using jQuery you can use .each() to iterate over your 3 data. Like this:
$.each(response.data, function(index, value) {
$("body").append('' + value.title + '');
$("body").append('<p class="date">Created: ' + value.created_formated +
'</p><br />');
});
jsFiddle example
.each() sanely loops over a collection of items. The first argument of .each(), is the object you want to loop over. This is response.data not merely response. This is because we want to look at response.data[0], response.data[1], and response.data[2]. The second argument of .each() is the callback function, or what we want to do with each of the items we are iterating over. Within the callback function, the first argument is automatically the index of the item (0, 1, or 2 in your case). The second argument is the value of the item. In your case this is a separate object: response.data[0], response.data[1], and response.data[2] respectively. We can use dot notation to retrieve the things we want directly from these objects. In the above example we access .path. .title and .created_formated from each of the values.
This make your entire function:
$.getJSON(base_url+'/ajax/get_itema/'+item_id+'/0/3/true', function(response) {
$.each(response.data, function(index, value) {
$("body").append('' + value.title + '');
$("body").append('<p class="date">Created: ' + value.created_formated +
'</p><br />');
});
});
Of course you probably want to append the response to (a) specific element/s.
Here's some good info on using .getJSON() to access multidimensional JSON data from another SO question.
Here's some general info about JSON in Javascript.
Note:
You need commas between your curly braces!
You have:
...p:\/\/domain.com\/yeah"}{"id":"4242","title"...
You need:
...p:\/\/domain.com\/yeah"}, {"id":"4242","title"...
I don't found in any answers that the data which you posted are NOT valid JSON string. Probably it is your main problem and the reason why $.get can not convert the server response to object. The objects inside the data array must be separated with commas. So the data must looks like
{
"total": "3",
"data": [
{
"id": "4242",
"title": "Yeah Lets Go!",
"created": "1274700584",
"created_formated": "2010-07-24 13:19:24",
"path": "http:\/\/domain.com\/yeah"
},
{
"id": "4242",
"title": "Yeah Lets Go!222",
"created": "1274700584",
"created_formated": "2010-07-24 13:19:24",
"path": "http:\/\/domain.com\/yeah222"
},
{
"id": "4242",
"title": "Yeah Lets Go!333",
"created": "1274700584",
"created_formated": "2010-07-24 13:19:24",
"path": "http:\/\/domain.com\/yeah333"
}
]
}
I recommend you allays verify JSON strings in http://www.jsonlint.com/.
Try a templating engine that convert the JSON to HTML on the browser.
You can have a look at pure.js, it is very fast, and keep the HTML totally clean of any Javascript templating logic.
We use it to generate all the HTML from JSON data in our web app.(Yep... I'm a main contributor to the lib)
If you are more familiar with the <%...%> or ${...} kind of templates, there are plenty of them and for any taste if you search on the web for javascript template.
using data from Oleg answer
var json = {} // your json data reformated by Oleg
for (var i = 0; i < json.data.length; i++) {
document.write('' + json.data[i].title + '');
document.write('<br>');
document.write('<p class="date">Created: ' + json.data[i].created_formated +'</p>');
document.write('<br>');
}
remember that the "data" is an array of object
Related
Let's say I already have a JSON string; perhaps I got it from the server.
data = '{"a": 1, "b": 2}'
I want to use postMessage or some other API which requires a JSON string and send it the information in the form
{ action: 'save', data }
Of course I could do
postMessage(JSON.stringify({ action: 'save', data: JSON.parse(data) });
but this ends up arsing the data and then immediately restringifying it as part of the stringified object being send to postMessage.
Is there any clean way to take advantage of the fact that I already have the stringified version of part of the data to be sent? I am concerned about this because actually data could be 100K or more in length and parsing it and stringifying it is not free.
Note: I know I could send the JSON string for data as is and have the receiving side parse it, but I cannot change the semantics of the receiving side.
Note 2: Of course I could also engage in various ways of building the JSON myself, such as
'{ "action": "save", "data": ' + data + '}'
but would prefer to avoid that.
You can try something like this:
var data = {
"a":"test1",
"b":"test2",
"c":{
"c1":"test3.1",
"c2":"test3.2"
}
}
var object = {};
object["action"] = "save";
object["data"] = data;
console.log(object);
I asked myself the same question and was pointed to here.
There are different solutions to this. I setup a little jsperf test.
Most promising aproach (if you don't need to have the thing nested) is removing the end and adding the stringified json:
var stringifiedObject = JSON.stringify({
some: 'random',
obj: 'propterties'
});
var res = JSON.stringify({
outer: 'object'
});
res = res.substring(0, res.length-1) + ', "alreadyString":' + stringifiedObject + '}';
I am passing a json encoded string in an ajax response to my Javascript. When I console.log the json, after JSON.Parse, it looks like the following:
[
{"732":
{
"doctor_name":"First M. Last ",
"degree":"MD"
}
},
{"377":
{
"doctor_name":"First M. Last ",
"degree":"MD"
}
},
{"1092":
{
"doctor_name":"First M. Last",
"degree":"DO"
}
},
{"759":
{
"doctor_name":"First M. Last",
"degree":"MD"
}
},
{"1628":
{
"doctor_name":"First M. Last",
"degree":"DO"
}
}
]
I need to access each one of these objects without knowing the ids (in this case "732", "377", "1092", "759", etc.)
Not sure if my data is even structured properly but I cannot even use Object.keys(obj) as it returns an error of a non-object property.
The way I am structuring my PHP array is as follows:
foreach ($doctors as $group){
$doctor_results[][(int)$group->prac_id]=array(
'doctor_name' => (string)$group->name,
'degree' => (string)$group->degree,
);
} // end foreach
I want each array id to be used as the key, not sure if this makes much sense.
TYIA
You most likely want your PHP to look like:
foreach ($doctors as $group){
$doctor_results[(int)$group->prac_id]=array(
'doctor_name' => (string)$group->name,
'degree' => (string)$group->degree,
);
} // end foreach
Note the missing [], which would imply pushing an item onto a numeric array. The second set of brackets in your example is suggesting to PHP that the numeric element created should be an associative array with an item with the 'prac_id' as a key. PHP is automatically creating that associative array, creating the structure with your key nested one level further in than you want for being able to grab an item by 'prac_id' by simple key access in JavaScript. As is, you'd need a nested loop like in Darren's answer.
I heavily agree with the comments posted by Marty and Six Fingered Man, but if you wanted to loop through the json, this would work:
jQuery.each(obj, function(index, data){
jQuery.each(data, function(id, fields){
console.log(id); // returns the ID's of the objects: 732, 377,....etc
console.log(fields); // returns the fields for each object. (doctor_name & degree)
});
});
JSFiddle Demo
[
{prac_id:"732",data:
{
"doctor_name":"First M. Last ",
"degree":"MD"
}
},...]
foreach ($doctors as $group){
$doctor_results[][(int)$group->{'prac_id'}]=array(
'doctor_name' => (string)$group->{'data'}->{'name'},
'degree' => (string)$group->{'data'}->{'degree'},
);
} // end foreach
Your ajax response is array of OBJECT. If you encode it by json_encode($array), your ajax response is OK. You can check your ajax response here : http://json.parser.online.fr/
So I think you can modify your ajax call. You can just add this dataType: 'json' in your ajax. It will automatically handle your JSON response.
$.ajax({
url: 'your_ajax_url',
data: 'data',
dataType: 'json',
success: function(data)
{
$.each(data, function(index, obj){
$.each(obj, function(id, nested_obj){
console.log("ID: "+id);
console.log("doctor name: "+nested_obj['doctor_name']+",degree:"+ nested_obj['degree'] );
});
});
}
)}
All,
I've got a function that basically gets triggered when an Upload finishes. I have the following code in that function:
onFinish: function (e, data) {
console.log(data.result);
},
When I do this I get the following response in my console:
[{
"name": "1_3266_671641333369_14800358_42187036_5237378_n.jpg",
"size": 35535,
"type": "image\/jpeg",
"url": "\/web\/upload\/1_3266_671641333369_14800358_42187036_5237378_n.jpg",
"thumbnail_url": "\/web\/upload\/thumbnails\/1_3266_671641333369_14800358_42187036_5237378_n.jpg",
"delete_url": "\/web\/upload.php?file=1_3266_671641333369_14800358_42187036_5237378_n.jpg",
"delete_type": "DELETE",
"upload_type": "video_montage"
}]
I'd like to get the value that is in the upload_type and do some actions based on that but I'm not sure how to get this from my function. Any help would be appreciated to get this information.
Thanks!
data.result is an array, you need to access the first element and then access upload_type.
Try console.log(data.result[0].upload_type);
Update:
If data.result is a string, you need to parse it first.Try
var result = JSON.parse(data.result);
console.log(result[0].upload_type);
You would access the upload_type property by the following:
onFinish: function (e, data) {
var uploadType = data.result[0].upload_type;
},
data.result[x] specifies to grab the object within the x key of your array. If you had multiple objects within your array then you would utilize a for loop to iterate each key.
To access the other properties you would follow the same principle. Based off of the desired action, you will handle the data appropriately.
Edit: What does the following return?
var obj = data.result[0];
for(var item in obj){
console.log(item + ': ' + obj[item]);
}
Demo: http://jsfiddle.net/yYHmQ/
I need help understanding the best way to manipulate a JavaScript data structure (if you call it that?). I come from a Perl background and am trying to iterate through a JavaScript data structure to update a div (or table) on the fly. Currently I'm just making the data a variable (data) to get going. once I have that sorted then I will use jquery's ajax methods to get the data as a json object on the fly. It's my understanding that the data structure I'm currently generating is the same thing I would get if it were json?? if not then I guess thats another question..
I have searched many times for such a tutorial but they are all close but haven't found one that meets my needs...
I would like to in the future be able to re-order the array and repopulate the #data_table div so part of my question is: is this even the best way to represent the data? Then I want to update just one part of the array like a companies phone number or add a person then redraw the div from this updated array...
The end result to the user could look like:
Company: 99 Beans, Auckland, Ph: 360499
People:
Matt, 6471
Christiaan, 6472
Michelle, 6473
Judy, 6474
Company: ....
* Next company and so forth..
My code so far is like this (except I have 500+ entries in the data array and only 2 here):
I have taken some of this code from another question I found here and tried to make it work for my type of structure..
<script>
$(document).ready(function() {
var r = new Array();
var data= [
{
"id":"6477",
"c":"99 Beans",
"ci":"Auckland",
"p":"09 360499",
"co":[
{"id":"6471","c":" NZ", "n":"Matt" },
{"id":"6472","c":" NZ", "n":"Chrstiaan" },
{"id":"6473","c":" NZ", "n":"Michelle" },
{"id":"6474","c":" NZ", "n":"Judy " },
{"id":"6475","c":" NZ", "n":"Kate " },
{"id":"6476","c":" NZ", "n":"Unknown Person" }
]
},
{"id":"7145", "c":"A1 Ltd", "ci":"Te Puke ","p":"06 870090",
"co":[{"id":"7145","c":" NZ", "n":"Alan" }
]
},
];
// this alert used to work, when I had the data as an array of arrays so there must be a problem with how I'm referencing it or my data structure is wrong??
alert (data.length + " companies" );//+ data[455].co[0].n);
var j = -1;
for (var key=0, size=data.length; key<size; key++) {
// first div
r[++j] ='<div>';
r[++j] = data[key].id;
r[++j] = ' - ';
r[++j] = data[key].c;
r[++j] = ' - ';
r[++j] = data[key].p;
r[++j] = '<br />';
//inner div
var k = -1 ;
for (var key1=0, size1=data[key].d.length; key1<size1; key1++) {
r[++j] ='<div>';
r[++j] = data[key].d.[key1].n + ' - ' + data[key].d.[key1].c + ' - ';
r[++j] = '</div>';
}
r[++j] = '</div>';
}
$('#data_table').html(r.join(''));
});
</script>
<div id="data_table"></div>
JSON's representation in Javascript is a javascript object.
var json = {
my_property: 2,
another_property: 'string!'
}
You can then fetch properties with json.my_property or json['my_property'] (which is nice if you don't know what exactly you are fetching, you can do var something = 'something-the-user-selected'; json[something]).
So, with jQuery, you would so something like this:
var json = {}; // get this from the server using $.AJAX() or $.getJSON()
$("#my_table").append("<tr><td>" + json.my_property + "</tr></td");
Or, if you got an array of, say, tweets, you should iterate over them, maybe with underscore's each, jQuery's each or plain old for (var i = 0; i < json.tweets.length; i++).
The data structure you are referring to is JSON.
With jQuery you can easily iterate your data structure with .each() and treat the returned value as an object with the attributes defined.
Here is a sample making the an Ajax call that will build your JSON object and iterating:
$.ajax({
type: "POST",
url: "MySite/MyResource",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if(data.d.length > 0){
$(data.d).each(function(){$('#mytable').append("<tr><td>Company: " + this.c + "</td></tr>");});
}
},
error: function (xhr, status, error) {
// do something appropriate
}
});
If you are looking to iterate farther then you can continue to call .each()
If data is your JSON value, this will format your specified string. (You'll have to JSONify your string to create it as the actual JSON object)
data.each(function(){
$('#mydiv').append('Company: ' + this.c + ', ' + this.ci + ', Ph: ' + this.p + ' People: ');
this.co.each(function(){$('#mydiv').append(this.n + ', ' + this.id);});
});
For the "rendering an JSON object to HTML", you may want to have a look at jQuery.template() which allows to render pieces of HTML with a template syntax. I have never used it so I do not know how well it can perform with very big lists... (also note that it is still in beta)
UPDATE
Here is a working example (it might not be optimal or anything) but you should see the general idea ;)
http://jsfiddle.net/tsimbalar/A9uYP/
UPDATE 2 for sake of completeness and traceability
There was a syntax error in the original code which prevented the alert() from executing (and all following code).
See comment :
Your code is not working because of a syntax error in
data[key].d.[key1].n., which is invalid syntax. (it should be data[key].d[key1].n, I suppose. Use the Firebug extension ofr Firefox to detect this kind of issues that would otherwise go unnoticed.
After fixing this typo, it is easy to iterate over the contents of the object using jQuery.each() as mentioned by catalpa in another answer. You can then build HTML elements (i.e. $("<div/>")) and append them to existing items of the page with append() . (see the fiddle about that part)
handlebars js templating is far better than jquery template and can be used for rendering complex json objects in html
I'm getting a JSON response from the server and i have to loop through the array in javascript and get the values. But I cant seem to loop throught it.
The JSON response of the array looks like this:
{
"1": "Schools",
"20": "Profiles",
"31": "Statistics",
"44": "Messages",
"50": "Contacts"
}
I just want to loop through it to get the ID and Name and populate some values on the page.
I have tried:
$.each(response, function(key, value) {
alert(key + ' ' + value);
});
// and
for (var key in response) {
alert(key + ' ' + response[key]);
}
But neither give the right values.
Thanks in advance for any help.
Reply:
Hi,
The response I'm getting with the second loop is:
0 {
1 "
2 1
3 "
4 :
5 "
6 S
etc etc
So that means its going through the whole response as a string and spliting it as key/value.
Thanks
Your problem is that you are not parsing the JSON string. Therefore, your foreach is going through the characters in the JSON string.
// If you are using jQuery.ajax, you can just set dataType to 'json'
// and the following line will be done for you
var obj = jQuery.parseJSON( response );
// Now the two will work
$.each(obj, function(key, value) {
alert(key + ' ' + value);
});
for (var key in obj) {
alert(key + ' ' + response[key]);
}
var response = {"1":"Schools","20":"Profiles","31":"Statistics","44":"Messages","50":"Contacts"};
for (var i in response) {
console.log(i + ' ' + response[i]);
}
Works just fine, how are you getting your response var?
You don't need to do like that, dealing with string is a boring job. You can make a object through the response.
1:json = eval(xmlHttp.responseText);
but this is unsafe in some degree.
json = JSON.parse(xmlHttp.responseText, function(key,value){// can do some other stuff here.});
then you can operate the variable as a normal object like this obj.a or obj["a"].
May this will help you.
http://jsfiddle.net/sG5sF/
jQuery.each works fine. So is for-each loop
http://jsfiddle.net/TfjrS/
Both of them work as they should. You might have errors in other parts of your code. Is the response variable set correctly to the JSON object given in your question? Are you checking the response statusCode? it should be 200 for a successful response?
Consider looking at How can I parse a JavaScript object with jQuery for a possible answer.
You can use for-in construct in pure Javascript. Of course, you need to be careful that you're only looking at the object's own properties (libraries like Prototype tend to pollute):
for(var key in response) {
if(response.hasOwnProperty(key)) {
...
}
}
EDIT
Are you using jQuery.ajax? What's the dataType value? It should be json. This might be why your response is being interpreted as a string. Also, when you console.log response, does it show up as a string or an object?