I am trying to parse some very basic JSON, but I don't know where I'm going wrong when trying to display it to the screen.
Am I not GRABBING the data correctly, such as, "data.re1Code"?
I hope someone can shed some light onto my basic question sorry.
JSON Data
[
{
"rep1FullName": "Justin Giesbrecht",
"rep1Code": "dc",
}
]
Javascript
$.ajax({
type: "GET",
url: "testJSONData.php",
dataType: "json",
success: function(data) {
$("#output").append(data.rep1FullName);
},
error: function () { alert("Error"); }
}); // End of generated json
The brackets [] make data a JSON array with your object as the 0th element so to get "Justin Giesbrecht" use the code: $("#output").append(data[0].rep1FullName); or remove the brackets and make the JSON:
{
"rep1FullName": "Justin Giesbrecht",
"rep1Code": "dc",
}
Your data is an array.
So you'd want
$("#output").append(data[0].rep1FullName);
You are returning a jSon array so you would need to access it via data[0].rep1FullName or return the jSon as below and then use data.rep1FullName
{
"rep1FullName":"Justin Giesbrecht",
"rep1Code":"dc"
}
Also, remove the last comma from the object notation.
[
{
"rep1FullName": "Justin Giesbrecht",
"rep1Code": "dc" // <-- No comma, breaks in IE if you have a comma.
}
]
Some of the other posters did this, but didn't mention it.
Related
I have a php class( ajax called) which returns json_encode data as
["2016-02-08 09:00:00.000","2016-02-15 09:00:00.000"]
I'm trying to do jquery.parseJSON(data) and it's giving me error "Unexpected number", what am I doing wrong?
You are trying to parse an array, not a string. JSON.parse (and any other JSON parser) expects a string, therefore Array.toString is called and your call becomes jquery.parseJSON("2016-02-08 09:00:00.000,2016-02-15 09:00:00.000")
//Error "Unexpected number", toString is called on the input array
JSON.parse(["2016-02-08 09:00:00.000","2016-02-15 09:00:00.000"])
// Returns an array object
JSON.parse('["2016-02-08 09:00:00.000","2016-02-15 09:00:00.000"]') // OK
If you are using the return of json_encode inline, you don't need to parse it, just assign it to a variable, JavaScript will do the parsing.
var dates = <?= json_encode($dates) ?>;
If you are using jQuery the data will typically already be parsed into JSON in the callback, if it doesn't, you can force it using dataType: 'json'
var x = '["2016-02-08 09:00:00.000","2016-02-15 09:00:00.000"]';
$.parseJSON(x) // return an array
jQuery does the decoding for you when you perform the AJAX call with the JSON dataType:
$.ajax({
url: 'mypage.php',
data: mydata,
dataType: 'json'
})
.done(function(response) {
// Response is an array, not a JSON string, jQuery decoded it.
// Demo:
console.log(response[0]); // "2016-02-08 09:00:00.000"
console.log(response[1]); // "2016-02-15 09:00:00.000"
}
This is explained in the jQuery docs:
dataType
...
"json": Evaluates the response as JSON and returns a JavaScript object.
So, don't use jquery.parseJSON on the result. It has already been done for you.
I am new to JSON.
In JS, I create an array of values like so:
var arrFields = $("td>.frmInput").map(function(){
return {
id: this.id,
value: $(this).val()
};
}).get();
I then AJAX them to the server like so:
$.ajax({
type: "POST",
url: "ajax/ax_all_ajax_fns.php",
data: "Fields=" +JSON.stringify(arrFields),
success: function(recd) {
alert(recd);
}
});
Note that there is a mixture of strings, plus the JSON.stringified (?) array. (There are additional string values sent, so data must remain as string.)
On the PHP side, I need to turn the received Fields string into an associative array.
Doing this:
$jsonAsStr_Fields = $_POST['Fields'];
die($jsonAsStr_Fields);
Returns this text string in the alert():
[{"id":"rateDriver","value":"Jacques Villeneuve"},{"id":"rateCar","value":"Chev"}]
Doing this:
$arrFields = json_decode($jsonAsStr_Fields, TRUE);
$driver = $arrFields['rateDriver'];
$car = $arrFields['rateCar'];
$tire = $arrFields['rateTire'];
die('Driver: [' .$driver. '] Car: [' .$car. '] Tire: [' .$tire. ']');
Returns this:
Driver: [ ] Car: [ ] Tire: [ ]
How can I turn the $jsonAsStr_Fields string into an assoc array, and thereby output the correct values to my alert?
Do this instead for your creation of values:
var arrFields = {};
$("td>.frmInput").each(function(){
arrFields[this.id] = $(this).val();
});
This will create an object, when JSON-stringified, that looks like this:
{"rateDriver":"Jacques Villeneuve", "rateCar":"Chev"}
Which seems to be the format you want to use in your PHP code.
You have an array of associative arrays and your arrays don't have the specified props, rateDriver for example is the value of the first array's element's id:
$driver = $arrFields[0]['id'];
$car = $arrFields[1]['id'];
For seeing the array's contents you use the famous var_dump function.
From the Author:
For those who haven't fully understood what solved this problem.
The underlying problem was that the stringified JSON was being modified en route (immed after hit Submit button en route to the PHP side) by the AJAX. All quote marks were being escaped, which made it impossible for that string to work with json_encode.
This was discovered by grabbing the value of the received data once it hit the PHP side:
$jsonAsStr_Fields = $_POST['Fields'];
die($jsonAsStr_Fields);
And alerting the received data in the AJAX success function:
success: function(recd) {
alert(recd);
}
Both of the above were described in the OP.
However, because I assumed this was an unrelated problem, I "fixed" the string displayed in the alert() box when I posted the question. Lesson to be learned: don't help - just post what you actually see.
It really displayed like this:
{\"id\":\"rateDriver\",\"value\":\"Jacques Villeneuve\"}
but I wrote that it displayed like this:
{"id":"rateDriver","value":"Jacques Villeneuve"}
Of course, the json_decode() PHP function had no idea what to do with the backslashes, so the string did not convert.
Solution was to use str_replace() on the received JSON string over on the PHP side, to resolve the problem, like this:
str_replace("\\", "", $_POST['Fields']);
I hope anyone can help me. My JSON isn't indexed (i.e. there isn't any key above any element)
[
{
"nome":"LABORGHINI GALLARDO",
"descrizione":"LAMBORGHINI GALLARDO ED. NERA- ANNO 2007- ",
"indirizzo_pubblicato":"autocaricateeea\/LABORGHINI GALLARDO31072013-023853\/LABORGHINI GALLARDO31072013-023853.json",
"indirizzo_immagine_copertina":"autocaricateeea\/LABORGHINI GALLARDO31072013-023853\/IMG_1414 (600x448).jpg",
"indirizzo_paginaauto":"autocaricateeea\/LABORGHINI GALLARDO31072013-023853\/index.html"
},
{
"nome":"RENAULT MEGANE",
"descrizione":"RENAULT MEGANE -ANNO 2006-DIESEL-CC. 1461",
"indirizzo_pubblicato":"autocaricateeea\/RENAULT MEGANE31072013-024103\/RENAULT MEGANE31072013-024103.json",
"indirizzo_immagine_copertina":"autocaricateeea\/RENAULT MEGANE31072013-024103\/P1080949 (600x450).jpg",
"indirizzo_paginaauto":"autocaricateeea\/RENAULT MEGANE31072013-024103\/index.html"
},
{
"nome":"FORD MONDEO",
"descrizione":"FORD MONDEO SINISTRATA- ANNO 2009- DIESEL- CC. 1997-",
"indirizzo_pubblicato":"autocaricateeea\/FORD MONDEO31072013-045216\/FORD MONDEO31072013-045216.json",
"indirizzo_immagine_copertina":"autocaricateeea\/FORD MONDEO31072013-045216\/P1080971 (600x450).jpg",
"indirizzo_paginaauto":"autocaricateeea\/FORD MONDEO31072013-045216\/index.html"
}
]
but after running unset() to remove an element with PHP the output JSON appears like this:
{
"1": // <--- **** add a key before an element
{
"nome":"Fiat Punto ",
"descrizione":"Fiat Punto Bianca",
"indirizzo_pubblicato":"autocaricateeea\/Fiat Punto 14072013-042703\/Fiat Punto 14072013-042703.json",
"indirizzo_immagine_copertina":"autocaricateeea\/Fiat Punto 14072013-042703\/P1080713 (600x450).jpg",
"indirizzo_paginaauto":"autocaricateeea\/Fiat Punto 14072013-042703\/index.html"
},
...........
...........
...........
How you can see there is a key before the element of JSON.
I know that this behavior is caused by unset (PHP json_encode as object after PHP array unset()).
There is a way to prevent this behavior?
had the same issue until i found this solution:
In addition to the array_values technique it is possible to use array_splice and remove an element and re-index in one step:
unset($a[1]);
Instead:
array_splice($a, 1, 1);
quoted from here: https://stackoverflow.com/a/3869219/4809658
The best way to do that is,
$json_arr = array_values($json_arr);
Although you have solved your issue at client side, I thought it would be helpful to show my solution to this issue using PHP, the idea is to construct a new array and exclude items that are not wanted, this way you will not have the indexing issue caused by unset, something like this:
$new_nodes= array();
for ($j = 0; $j < count($composition->nodes); $j++)
{
//exclude some nodes
if ($id!= $composition->nodes[$j]->id)
{
// store only the nodes that you want:
array_push($new_nodes, $composition->nodes[$j]);
}
}
// and finally, use the new modified nodes array:
$composition->nodes= $new_nodes;
Why do you need to prevent this behavior? When you convert the json to a PHP array, regardless of the JSON format is going to be an index array (have the numbers you shown) regardless.
If the numbering is incorrect use http://php.net/manual/en/function.array-values.php to fix.
Regenerated your json with this PHP script
<?php
$arr = array
(array('nome' => 'LABORGHINI GALLARDO',
'descrizione' => 'LAMBORGHINI GALLARDO ED. NERA- ANNO 2007-',
'indirizzo_pubblicato' => 'autocaricateeea/LABORGHINI GALLARDO31072013-023853/LABORGHINI GALLARDO31072013-023853.json',
'indirizzo_immagine_copertina' => 'autocaricateeea/LABORGHINI GALLARDO31072013-023853/IMG_1414 (600x448).jpg',
'indirizzo_paginaauto' => 'autocaricateeea/LABORGHINI GALLARDO31072013-023853/index.html'),
array('nome' => 'RENAULT MEGANE',
'descrizione' => 'RENAULT MEGANE -ANNO 2006-DIESEL-CC. 1461',
'indirizzo_pubblicato' => 'autocaricateeea/RENAULT MEGANE31072013-024103/RENAULT MEGANE31072013-024103.json',
'indirizzo_immagine_copertina' => 'autocaricateeea/RENAULT MEGANE31072013-024103/P1080949 (600x450).jpg',
'indirizzo_paginaauto' => 'autocaricateeea/RENAULT MEGANE31072013-024103/index.html'),
array('nome' => 'FORD MONDEO',
'descrizione' => 'FORD MONDEO SINISTRATA- ANNO 2009- DIESEL- CC. 1997-',
'indirizzo_pubblicato' => 'autocaricateeea/FORD MONDEO31072013-045216/FORD MONDEO31072013-045216.json',
'indirizzo_immagine_copertina' => 'autocaricateeea/FORD MONDEO31072013-045216/P1080971 (600x450).jpg',
'indirizzo_paginaauto' => 'autocaricateeea/FORD MONDEO31072013-045216/index.html')
);
$arr_json = json_encode($arr);
var_dump($arr_json);
?>
Preferably the JSON may be parsed with JS so that the required car is accessed. There is no need to modify the JSON with PHP.
I searched and tried anyway to implement the behaviour that i searched in my question but i didn't find nothing. I supposed that, like you can see in this answer, unset function adds indices to the array because the JSON_encode not support arrays with hole. So, to solve my problem, i load the JSON file with a jQuery function, delete the elements with jQuery and i call a ajax function to delete the files linked at the address contained in the json file:
$.getJSON('loadauto.json', function(result) {
var y = result;
$.each(result, function(i, field){
if(field.indirizzo_paginaauto == x){
delete result[i];
}
});
$.ajax({
async: true,
cache: false,
type: 'POST',
url: 'deleteauto.php',
data: { nuovofilejson: y, indirizzo: x},
success: function(data) {
alert ("Auto cancellata definitivamente");
},
error: function(data) {
alert ("Error");
}
});
}
Here is my PHP code, it's getting a listing of collections from mongodb
$list = $db->dbname->listCollections();
$result = array();
$i=0;
foreach ($list as $thiscollection) {
$result[$i++] = $thiscollection->getName();
}
echo json_encode( $result );
I do console.log in the callback and this is what I see.
["fruits", "dogs", "cars", "countries"]
The problem is that this is a string, not an array. I need to iterate through these values. How an I make this into a real object or get php to give me json rather than php array so I can use parseJSON on it.
Thanks.
js:
$.post('/ajax-database.php', function (data) {
console.log($.parseJSON(data));
$.each(data, function (key, value) {
console.log(value);
});
});
I see you are using jquery, if you want data to come back to you as a json object you need to do 1 of 2 things.
add header("Content-Type: application/json") to your php file, this will tell jquery to convert it to a json object instead of as text
Add a forth parameter to your $.post,
$.post('/ajax-database.php', function (data) {
console.log($.parseJSON(data));
$.each(data, function (key, value) {
console.log(value);
});
}, "json");
that will tell jquery to call your error handler if its NOT json, like if your php code fails and outputs html instead. You really should use $.ajax, i have no idea why anyone uses $.post, you can't do ANY meaningful error handling.
JSON is strings. If you want to be able to iterate over it then you need to decode it.
What are those #attributes thing I have in my JSON file and how can I read that with JQuery?
The JSON "text" I use is produced with json_encode in PHP from an array of custom objects.
Here's a reduced JSON file:
{ "movies" : [ { "url":"http:\/\/www.youtube.com\/watch?v=Nsd7ZcXnL6k", title":{"#attributes":{"type":"text"},"0":"**Title here**"} ] }
I can read the URL easily with the following code :
$.getJSON(url, function(json){
$.each(json.movies,function(i,item) {
alert(item.url);
});
});
How can I read the title Title here value ?
UPDATE
Well, I still don't know what the #attributes are, but I know why they were in my final JSON file. I was using $sxml = simplexml_load_file($feedURL); to read a XML and then $sxml->title to read a title, wich is not a string apparently but some kind of PHP object.
Instead of
$this->title = $sxml->title
I used
$this->title = $sxml->title . ""
(Ot's converting the object into a string value). Maybe there's a more intelligent way of doing this?
If you have a recent PHP, it supports casting, so you can use
(string)$xml->title
and it'll work.
$.getJSON(url, function(json){
$.each(json.movies,function(i,item) {
alert(item.url);
alert(item.title[0]);
});
});