I have a JSON data which is something like the following ::
{"product":["{productTitle=ABCD , productImage=/abcd.jpg, productPath=CDEF.html, productPrice=$299}","{productTitle=EFGH, productImage=xxxx.jpg, productPath=ggfft.html, productPrice=$299}"]}
I my JSP page I am trying to process the data and use it .
Following is the function that I am using to parse each node of the response .
success : function(data) {
alert("successs");
alert('data.product' + data.product);
$.each(data.product, function(index) {
alert(data.product[index].productTitle);
});
},
Here alert('data.product' + data.product);
gives me the alert with the whole JSON which is under the product node .
alert(data.product[index].productTitle);
-- This alert is showing as "undefined" .
I need help to parse it the JSON and print each of the "productTitle"
Thanks in advance .
JSON.parse(data)
should do the trick.
Edit: I see that it is not even JSON inside the string. Use Musa's answer to transform it into JSON and then use JSON.parse(data)
as I suggested initially.
try this
var jdata = JSON.parse(data);
$.each(jdata.product, function(index, productdetail) {
alert(productdetail.productTitle);
});
data.product
is an array of strings not objects or JSON, you'll have to parse the strings to get the data.
you can use regex to transform the string to JSON an then JSON.parse or $.parseJSON to convert it to js objects but its a bit messy, see http://jsfiddle.net/nQE6J
$.each(data.product, function(index) {
alert(JSON.parse(data.product[index].replace(/=/g, ':').replace(/([a-z\.A-Z\$\/\d]+)/g, '"$1"')).productTitle);
});
The json you give is
{
"product":[
"{productTitle=ABCD , productImage=/abcd.jpg, productPath=CDEF.html, productPrice=$299}",
"{productTitle=EFGH, productImage=xxxx.jpg, productPath=ggfft.html, productPrice=$299}"
]
}
However you have to change above into
{
"product":[
{"productTitle":"ABCD" ,
"productImage":"/abcd.jpg",
"productPath":"CDEF.html", "productPrice":"$299"},
....
]
}
Sodata.product[0].productTitle
is "ABCD"
Add
contentType : "application/json"
to you request (and in the Response header, which should be done automatically by your webserver). jQuery then automatically interprets the Repsonse as JSON object and parses it.