Parse JSON in Javascript from PHP - javascript

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'] );
});
});
}
)}

Related

How do I map a variable to object

I'm new to JSON and jQuery/JavaScript.
How would I pull in a object so that I can use it within jQuery, I've tried 2 attempts
var placements = document.querySelector(placements)
var message = document.querySelector(placements.message)
$.ajax({
type: 'GET',
url: 'https://raw.githubusercontent.com/kieranbs96/developer-exercise/master/data/recommendations.json',
async: false,
dataType: 'json',
success: function (data) {
$("header").append(placements.message);
}
});
Below is the JSON I'm trying to pull in:
{
"placements":[
{
"message":"If you like this, you might be into these",
"items":[
{
"id":"029148",
"name":"Woodblock Play Suit",
"price":"46.00"
},
{
"id":"0294526806",
"name":"Smock Dress",
"price":"39.00"
},
{
"id":"0297180006",
"name":"Cami",
"price":"9.00"
},
{
"id":"0298473606",
"name":"Asymmetric Wrap Cami Dress",
"price":"46.00"
},
{
"id":"0297155306",
"name":"Casual Stripe Tee",
"price":"16.00"
}
]
}
]
}
Marked as duplicate - the other question did not solve my problem - it has been solved by an answer to this question.
You haven't included what the error is or the expected output, but here's two potential errors.
You aren't utilizing the data object returned from your AJAX request.
The value associated with the placements key on your JSON object is an array of objects. Therefore, to access the message key, you'll need to traverse the array.
This is likely what your code should look like:
$("header").append(data.placements[0].message);
First off, you're missing the data object within your append function.
Second, you're missing the key notation of data.placements considering the fact that placements is an array.
You can either use data.placements[0].message to get your preferred data, or, if placements will be extended with more objects in the future, map through your objects like this:
data.placements.map(function(obj, index){
if(index == 0){
$("header").append(obj.message);
}
})
Not necessary if your array will always have a length of 1 of course

Ajax multiple object return - Parsing

I am unable to parse the multiple object JSON on ajax success. But I can, when I receive a single object JSON.
Ajax call
$.ajax({
url: "ajax/filter.php",
dataType: "JSON",
type: "POST",
data: {
category: $categoryArr,
brand: $brandArr,
occasion: $occasionArr,
colour: $colourArr,
price_min: $price_min,
price_max: $price_max
},
success: function(data) {
data = JSON.parse(data);
$("#result").html(data["name"]);
}
});
PHP code for single object JSON
$products = R::findOne('products', $filterString, $filterArray); //returns single row from db
if (!empty($products)) {
echo $products;
} else {
echo "No Products are available for this search criteria";
}
Result: {"id":"1","name":"Malbari-Product1","brand_id":"1","category_id":"1","colour_id":"2","occasion_id":"2","price":"599","discount":"10","small_img":"images/products_small/1.png","big_img":"images/products_big/1.jpg","seller_id":"1"}
PHP code for multiple object JSON
$products = R::find('products', $filterString, $filterArray); //returns multiple rows from db
if (!empty($products)) {
echo $products;
} else {
echo "No Products are available for this search criteria";
}
Result: {"id":"1","name":"Malbari-Product1","brand_id":"1","category_id":"1","colour_id":"2","occasion_id":"2","price":"599","discount":"10","small_img":"images/products_small/1.png","big_img":"images/products_big/1.jpg","seller_id":"1"} {"id":"10","name":"Malbari-Product6","brand_id":"2","category_id":"1","colour_id":"1","occasion_id":"5","price":"350","discount":null,"small_img":"images/products_small/6.png","big_img":"images/products_big/6.jpg","seller_id":"2"}
I suppose, in case of multiple objects, i'm actually getting a single string instead of multiple object JSON.
Please help.
wouldn't you just want to return an array of JSON objects?
[ { "Name": "Object1" }, { "DifferentObject": "Object2" }]
Based on your comments, it seems that the problem is with the php find() and findOne() methods.
In order to use them both in the same way, it would be convenient to make sure both methods return a similar result like an array with either one or more objects in it. That way you can use them both the same way in your javascript.
What I would do, is create an empty array and add the results as objects in that array. You can return that array from your methods and where you now echo your results or error message out, you simply do an echo json_encode($function_result_or_error_message);. I would probably add an error key and message to the array before I do that to have the error message contained in the result.
For more details you would have to post your php find() and findOne() methods.

json result display first value

I have found several posts similar to this topic but nothing I have tried has actually worked. My question is simple and should be easy to answer. My return json object will have one key and one value. For my code below, the alert shows "[{"DISCOUNT":1}]" and all I am trying to do is parse out the "1" and display it. Ultimately, I want to plug that value into a variable and use for multiplication, but I can't even get the darn number to display by itself. My code is below:
function codeMatchTest() {
if ($('#dbReturnString').val() == '') {
alert("Please enter a discount code.");
} else {
$.ajax({
type: "POST",
url: "PROMO.svc/MatchCode",
contentType: "application/json",
dataType: "json",
data: JSON.stringify({ codeInput: $('#dbReturnString').val().toLowerCase() }),
success: function (json) {
alert(json.d);
/*alert (json.d.discount); // getting "undefined"
$.each(json.d, function (key, value) {
var discount = value;
});
alert("Success: " + discount); //getting "undefined" */
},
error: function () {
alert("There was an error with your request.");
}
});
}
}
I have found no good references on how to actually use the data in a json object. My json object will only consist of a single key and value and I will only ever need to use the value.
Also, I have tried several iteration using $.each and none work. Based on the jquery documentation, it should be very easy but I am having not luck.
If your alert is showing "[{"DISCOUNT":1}]" that means you have an object within an array.
try alert(json.d[0].DISCOUNT);
JSON parsed objects are case sensivetive, plus its seems that json.d contains a string (wich seems to be in json) rather than an object. Try:
var discount = JSON.parse(json.d);
discount = discount[0].DISCOUNT;
success: function(json) {
alert(json.d[0]["DISCOUNT"]);
}
First comment on your code, you are reinventing what jQuery does.
data: JSON.stringify({ codeInput: $('#dbReturnString').val().toLowerCase() }),
It should just be
data: { codeInput: $('#dbReturnString').val().toLowerCase() },
Now to get the data it is simple, you are returning an array with an object in it.
Let us look at it as a regular variable and not an Ajaqx call.
var json = [{"DISCOUNT":1}];
So you got an array? How do you get the object inside of it? You reference the index. Since you said there will only be one index being returned, than use [0] to access it.
success: function (json) {
alert(json[0].DISCOUNT);
To access the first item from the json you may use
alert(json.d[0].DISCOUNT);
Because json.d is an array and it contains one object which is 0 index. So, json.d[0] will select the first item/object from the array and using .DISCOUNT you can access the object's property. It's also possible to access the property like
alert(json.d[0]["DISCOUNT"]);
Try this way
You can use JSON.parse(json.d) / json.d
var data = json.d;
for(i=0;i<data.length;i++) {
alert(data[i].fieldname);
}

.each parse JSON returns undefined

Hi I have the following codes:
$.ajax({'type':'POST', 'url':'https://www.123.com/site/gethistory',
'data':{'a': this.username, 'b': username},
'success':function(history){
alert(history);
var codes = jQuery.parseJSON(history);
$.each(codes, function(key, value) {
alert(key);
}); //each
},
'error':function(){
}
}); //ajax
Right now the key is undefined. And i tried to alert(value.text), it still gives me undefined.
history is alerted as this:
[{"demo":{"text":"hi
man","time":"1380167419"},"admin":{"text":"hi","time":"1380167435"},"demo":{"text":"this
works flawless now.","time":"1380167436"},"demo":{"text":"we are
basically done with this/","time":"1380167443"}}]
It works fine in this fiddle. However, there is a problem with your JSON.
Although it is syntactically correct, it is structured such that you are returning an array of one object with a number of properties all with the same name:
[
{ "demo":{
"text":"hi man",
"time":"1380167419"
},
"admin":{
"text":"hi",
"time":"1380167435"
},
"demo":{
"text":"this works flawless now.",
"time":"1380167436"
},
"demo":{
"text":"we are basically done with this/",
"time":"1380167443"
}
}
]
Each successive demo will overwrite the previous one, so you'll only see the last demo property.
Looks like there is something wrong with your JSON. Try alert codes and make sure the parsed JSON is in the right format, i.e key/value pairs
no need to use jQuery to parse JSON. Just var codes = JSON.parse(history)
$.each(codes, function(k, v){
console.log(v )
});

How to parse json string to javascript object

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

Categories