i have a json format like
[
{
id: 15,
diemdung: "a"
},
{
id: "16",
diemdung: "b",
khoangcach: "300",
pho: "c",
da: [
{
lancan: "d",
kc: "333"
},
{
lancan: "e",
kc: "322"
}
]
},
...
]
i using php like print json_encode($rows);
and i try to read it at client using jquery like
$.getJSON(url,function(json){
$.each(json,function(key, val){
$.each(this.da,function(){
alert(this.kc);
});
});
});
but it's not working. How i do that? thanks
If your code is otherwise working, you may be getting the following error:
TypeError: obj is undefined
This is because the first object in the outer array does not have a value for the "da" property. Before you try to loop over the array held by the "da" property, you should check if it exists.
Try:
$.getJSON(url,function(json){
$.each(json,function(){
if (this.da) {
$.each(this.da,function(){
alert(this.kc);
});
}
});
});
$.each(json, function(arrayID, arrayVal) {
//alert(arrayVal.id);
$.each(arrayVal.da, function(daKey,daData) {
alert(daData.kc);
});
});
Heres my same SO question a while ago for further code
JQuery $.each() JSON array object iteration
edit to rename some variables to make clearer
For n level hierarchy
var str = '{"countries":[{"name":"USA","grandfathers":[{"gFName":"Steve","grandfathersKid":[{"gFKName": "Linda","kid": [{"name": "Steve JR", "friends": [{"name": "Kriss|John|Martin|Steven"}]}]}]}]}]}';
var obj = jQuery.parseJSON(str);
parseJsonString(obj);
Function :
function parseJsonString(data){
$.each(data, function(index, val){
if($.type(val) == 'object' || $.type(val) == 'array'){
product.parseJsonString(val);
}else{
alert(index + ' - ' + val);
}
});
}
Related
I successfully (tested) call an ajax request to a php script. This is the portion of code i need to make working:
success: function (response, status) {
$.each(response, function (i, item) {
alert(item.id);
item.id is just...nothing.
This is the generated - json_encoded array by php page:
[
{
"conto": "1"
},
{
"id": "4",
"activity_id": "50",
"path": "Testo/base.png",
"title": "Ffgf",
"descrizione": "Tttt"
},
{
"id": "8",
"activity_id": "50",
"path": "Testo/61FCFUX_IMG_0536.PNG",
"title": "Hggggg",
"descrizione": "Tgg"
}
]
What do I do wrong?
p.s: if you noticed, this is an array merge between two arrays: the first one just reports "conto" in in, the other one is a list generated by fetching elements by database.
Your first array not containing id so you are getting undefined value. Skip first array:
$.each(response, function (i, item) {
if(i==0)
{
alert(item.costo);
}
else
{
alert(item.id);
//Or better to use console
console.log(item.id);
}
});
I believe your issue is with your reference. Since your JSON object contains an array you will need to reference it with subscripts. Try changing item.id to item[i].id. That way as the each function iterates through the array, it can reference the id field in each object.
Edit: Here's working code.
$(document).ready(function (){
var source = '[{"conto":"1"},{"id":"4","activity_id":"50","path":"Testo\/base.png","title":"Ffgf","descrizione":"Tttt"},{"id":"8","activity_id":"50","path":"Testo\/61FCFUX_IMG_0536.PNG","title":"Hggggg","descrizione":"Tgg"}]';
source = JSON.parse(source);
var cellcount = length(source);
for(var i = 0; i < cellcount; i++){
console.log(source[i].id);
}
});
function length(obj) {
return Object.keys(obj).length;
}
I have Express running on a custom node API that breaks down a large JSON into bite sized chunks for mobile usage.
One of the section goes through a mass of items and returns only one of them. However the returned data is still wrapped in [ .. ] which makes working with it tough.
My NODE.JS code snippet that deals with my routed request
app.get('/ppm/detail/operators/:operatorCode', function (req, res) {
var with_operatorCode = ppm.RTPPMDataMsgV1.RTPPMData.OperatorPage.filter(function (item) {
return item.Operator.code === req.params.operatorCode;
});
res.json(with_operatorCode);
});
so if you access the url
http://(domain)3000/ppm/summary/operators/25
the following data is returned
[
{
"code": "25",
"keySymbol": "",
"name": "First Great Western",
"Total": "577",
"PPM": {
"rag": "G",
"text": "94"
},
"RollingPPM": {
"trendInd": "+",
"displayFlag": "Y",
"rag": "G",
"text": "97"
}
}
]
How can I break that object out of the [ .. ] so it is not returned as an array object and only shows as
{
"code": "25",
"keySymbol": "",
"name": "First Great Western",
"Total": "577",
"PPM": {
"rag": "G",
"text": "94"
},
"RollingPPM": {
"trendInd": "+",
"displayFlag": "Y",
"rag": "G",
"text": "97"
}
}
Alternativly, how can I work with the [ .. ] object in PHP? When I am trying to echo it using
$operatorJSON=file_get_contents("operator.json");
$operator=json_decode($operatorJSON);
echo $operator->PPM->text;
It errors if the JSON has the [ ]
I suspect it is being treated as an array object
UPDATE : I tried to flatten the array
app.get('/ppm/detail/operators/:operatorCode', function (req, res) {
var with_operatorCode = ppm.RTPPMDataMsgV1.RTPPMData.OperatorPage.filter(function (item) {
return item.Operator.code === req.params.operatorCode;
});
var obj = arr.reduce(function(x, y, i) {
x[i] = y;
return x;
}, {});
res.json(obj(with_operatorCode));
});
but the object returned is still in [ ]
If i understand correctly , i think the most easy way is use the index to get the element in array
res.json(with_operatorCode[0]);
Of course, the [foo] denotes that it is an array.
You could address the item as [0], but that is more likely to cause an error, if no item exists in the filter:
On the php side:
$operator=json_decode($operatorJSON);
echo $operator[0]->PPM->text;
On the Node side:
res.json(with_operatorCode[0]);
The smarter thing to do would be to handle it as an array:
$operator=json_decode($operatorJSON);
if (is_array($operator) && count($operator))
{
echo $operator[0]->PPM->text;
}
Or, if filter may give you more than one:
$operator=json_decode($operatorJSON);
foreach ($operator as $op)
{
echo $op->PPM->text;
}
Try for this:
function toObject(arr) {
var obj = {};
for (var i = 0; i < arr.length; ++i)
obj[i] = arr[i];
obj rv;
}
I am using jquery and getJSON to GET a data feed constructed by PHP. The Feed displays fine when visiting the PHP page. The problem I am running into is that the JSON feed returns as multiple objects when it is GET requested in jQuery, and I don't know how to write the jQuery to display all objects and their data.
jQuery:
$(document).ready(function () {
$("#display_results").hide();
$("#searchButton").click(function (event) {
$("#display_results").show();
event.preventDefault();
search_ajax_way();
});
$("#search_results").slideUp();
$("#searchBox").keyup(function (event) {
$("#display_results").show();
});
});
function search_ajax_way() {
//var search_this=$("#searchBox").val();
//$.post("http:/url.com/folder/cl/feed.php", {city : search_this}, function(data){
//$("#display_results").html(data);
//});
var search_this = $("#searchBox").val();
$.getJSON('http://url.com/app/cl/disp_byowner_feed.php', {
city: search_this
}, function (result) {
$.each(result, function (i, r) {
console.log(r.seller);
window.title = r.title;
window.seller = r.seller;
window.loc = r.location;
(Plan on listing all keys listed in the data feed below here)
});
console.log(result);
$("#display_results").html(window.seller + < need to list all keys / values here > );
});
}
PHP (Constructs JSON Feed):
$city = 'Kanosh';
$s = "SELECT * FROM `list` WHERE `city` LIKE '%".$city."%'";
$res = $mysqli->query($s) or trigger_error($mysqli->error."[$s]");
$a = array();
while($row = $res->fetch_array(MYSQLI_BOTH)) {
$a[] = array(
'title' => $row['title'],
'price' => $row['price'],
'rooms' => $row['rooms'],
'dimensions' => $row['dimensions'],
'location' => preg_replace('pic\u00a0map', '', $row['location']),
'price' => $row['price'],
'address' => $row['address'],
'seller' => $row['seller'],
'href' => $row['href'],
'date' => $row['date']
);
}
header('Content-Type: application/json');
echo json_encode($a);
$res->free();
$mysqli->close();
Sample JSON Feed:
[{
"title": "Great Ski-In Location with Seller Financing Available ",
"price": " (Park City near the Resort) ",
"rooms": "",
"dimensions": "",
"location": "",
"address": "Crescent Road at Three Kings Dri",
"seller": "real estate - by owner",
"href": "http:\/\/saltlakecity.craigslist.org",
"date": "20140811223115"
}, {
"title": "Prospector Building 1 - Tiny Condo, Great Location - Owner Financing",
"price": "$75000",
"rooms": false,
"dimensions": "",
"location": " Prospector Square Park City Ut",
"address": "",
"seller": "real estate - by owner",
"href": "http:\/\/saltlakecity.craigslist.org",
"date": "20140811223115"
}]
Your output is an Array of JSON objects.
Fortunately, JavaScript is convenient for manipulating JSON (actually, that is why JSON was created..), and jQuery is convenient for manipulating the DOM.
To parse the result, you can just iterate through that Array, construct whatever HTML string that you need within the Array, and then insert it into the DOM using jQuery.
Here a simple example with lists :
var html = "";
for (var i = 0; i < result.length; i++) { //assuming result in the JSON array
html += '<ul id = 'house_' + i>';
for (var property in result[i]) { //read all the object properties
html += '<li>' + property + ' : ' + result[i][property] + '</li>';
}
html += '</ul>';
};
$("whatever_div").html(html);
If you only want to display some of the properties, you can read them separately and do additional formatting (for the date for example).
It is also useful to give the different HTML objects ids corresponding to what they represent.
function search_ajax_way(){
//var search_this=$("#searchBox").val();
//$.post("http:/url.com/folder/cl/feed.php", {city : search_this}, function(data){
//$("#display_results").html(data);
//});
var search_this=$("#searchBox").val();
$.getJSON('http://hooley.me/scraper/cl/disp_byowner_feed.php', { city : search_this }, function(result) {
var output = '';
$.each(result, function(i,r) {
output+= r.title + " " + r.seller
});
$("#display_results").html(output);
});
}
I have an index.html file that calls main.php which returns a json object just fine.
main.php returns this
{
"products": [
{
"id": "1",
"txt": "Bar",
"image": "",
"page": ""
},
{
"id": "2",
"txt": "Car",
"image": "",
"page": ""
},
{
"id": "3",
"txt": "Far",
"image": "",
"page": ""
}
],
"success": 1
}
in Java there is json.getJSONArray(TAG_PRODUCTS);
but.... I am using HTML and javascript here...
so in my html file I have the following
how do I pull the products array out of my json returned data?
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost:8888/HelloWorld/main.php',
contentType: "application/json; charset=utf-8",
success: function (data) {
var names = data
$('sa_content').append('<select name="input_4">');
$.each(data, function(index, element) {
alert( "index: " + index + ", element.cf_id: " + element );
});
$('sa_content').append('</select>');
},
error: function(){
$('#sa_content').append('<li>There was an error loading the feed');
}
});
When I run the index.html page I get the following alerts
index = products, element = [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
and
index = success, element = 1
So how do I pull the products array out of the json and iterate through it to get the values of id, txt, image, page?
Thanks in advance for your time.
Dean-O
Try using this as the success function:
function (data) {
var products = data.products;
for (var i = 0; i < products.length; i++) {
var product = products[i];
alert(product.id + " " + product.txt + " " + product.image + " " + product.page);
}
}
It should iterate through all the products and alert you the data.
Then you can modify the code to suit your needs.
You either use JSON.parse, or simply eval('(' + json + ')'); if you are certain the code is safe.
You're getting an array of products, so you want to iterate over that array:
success: function (data) {
var names = data
for(i = 0; i < data.products.length; i++) {
//Do what you want.
var id = data.products[i].id;
}
}
If your page returns ONLY json, then the XHR object that comes back from your jquery ajax should contain a javascript object constructed from that data. If that is not the case, something is wrong with your page, such as returning more than a json encoded string.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Loop through Json object
I have a PHP function, data.php, which fetches JSON data from an external server URL like such:
<?php
$url = "https://dev.externalserver.net/directory";
$content = file_get_contents($url);
echo json_encode($content);
?>
The JSON array retrieved looks like the following:
[
{ "name": "Not configured",
"mac_address": "1111c11c1111",
"online": "false",
"rate": "Not configured" },
{ "name": "Not configured",
"mac_address": "0000c00c0000",
"online": "false",
"rate": "Not configured" }
]
I'm now trying to write an AJAX call to that PHP function, iterate through the JSON array, and display it in the browser in non-JSON formatting. My AJAX code looks like the following:
$.ajax({ url: 'data.php',
type: 'POST',
dataType: 'json',
success: function(output) {
$.each(output, function() {
$.each(this, function(key, value){
alert(key + " --> " + value);
});
});
}
});
My issue is that code is currently displaying alert boxes that show the individual characters within the array like such: 0 --> [ , 0 --> , 0 --> { ... etc etc
Is there a problem with how I'm passing the data using json_encode(); and dataType: 'json' or does the issue resolve with how I'm iterating through the array?
Thanks.
Other responders missed the sneaky but still obvious bit, that what's coming back from the resource being polled in the PHP is probably already valid JSON, and re-encoding it is causing the browser to interpret it merely as a string. In this case, the javascript never had a chance.
Remove the json_encode() bit in the PHP and just echo what comes back, and see if that doesn't improve things.
I think your problem is the this in the second each. Try:
$.each(output, function(key, value) {
$.each(value, function(key, value){
alert(key + " --> " + value);
});
});
var jsonArray = [
{ "name": "Not configured",
"mac_address": "1111c11c1111",
"online": "false",
"rate": "Not configured" },
{ "name": "Not configured",
"mac_address": "0000c00c0000",
"online": "false",
"rate": "Not configured" }
];
$.each(jsonArray, function() {
for (var key in this) {
if (this.hasOwnProperty(key)) {
console.log(key + " -> " + this[key]);
}
}
});
take a look at this
How do I loop through or enumerate a JavaScript object?