PHP json_encode versus JAVASCRIPT JSON.parse - javascript

If I create in PHP a json like this:
if ( ($result = mysqli_query($link, $sql)) && (mysqli_affected_rows($link)!==0) ) {
$entries = array();
while ($row = mysqli_fetch_assoc($result)) {
$entries[] = $row;
}
$data = json_encode($entries);
echo($data);
I will get this result:
[
{"id":"100043","title":"Mini for Sale","session":"1407456000","totalViews":"0"},
{"id":"100000","title":"test","session":"1408366541","totalViews":"4"},
{"id":"100001","title":"Le Cappa","session":"1408377143","totalViews":"0"},
{"id":"100002","title":"Le Cappa","session":"1408378069","totalViews":"0"},
{"id":"100003","title":"test","session":"1408378833","totalViews":"0"}
]
If I do this with JavaScript: console.log("jsondata: ", JSON.parse(data));
(where data is the json above: data = [{"id ... )
I will get this result:
jsondata: [
Object { id="100043", title="Mini for Sale", session="1407456000", mehr...},
Object { id="100000", title="test", session="1408366541", mehr...},
Object { id="100001", title="Le Cappa", session="1408377143", mehr...},
Object { id="100002", title="Le Cappa", session="1408378069", mehr...},
Object { id="100003", title="test", session="1408378833", mehr...}]
My question: Why is this different and how can I get with PHP a json with objects like the javascript one?
Some more Information: I'm trying to implement a table with the dynatable plugin. It works only if I pass the Data sended by PHP again with JSON.parse. Thats means to me that the PHP-json is wrong.
$.ajax({
url: 'http://huntinggrounds.de/stats/test.php',
success: function(data){ console.log("data: ",data); console.log("jsondata: ", JSON.parse(data));
$('#my-final-table').dynatable({
dataset: {
records: JSON.parse(data)
}
});
}
});
Here are booths results copied from console.
data: [{"id":"100043","title":"Mini for Sale","session":"1407456000","totalViews":"0"},{"id":"100000","title":"test","session":"1408366541","totalViews":"4"},{"id":"100001","title":"Le Cappa | Franco Gravante","session":"1408377143","totalViews":"0"},{"id":"100002","title":"Le Cappa | Franco Gravante","session":"1408378069","totalViews":"0"},{"id":"100003","title":"test","session":"1408378833","totalViews":"0"}]
jsondata: [Object { id="100043", title="Mini for Sale", session="1407456000", mehr...}, Object { id="100000", title="test", session="1408366541", mehr...}, Object { id="100001", title="Le Cappa | Franco Gravante", session="1408377143", mehr...}, Object { id="100002", title="Le Cappa | Franco Gravante", session="1408378069", mehr...}, Object { id="100003", title="test", session="1408378833", mehr...}]

What you're seeing in the console is an interactive debug representation of an actual Javascript object in memory. Is is not JSON. Your PHP output already is the perfect JSON representation of that Javascript object.

Related

Structured data

Hello I am working on the data structure. I have following problems:
when I dump ($ data), I have all the info.
I am looking for how has integrated a php variable in json.
here is my piece of code. I have serious problem with concatenation. thank you in advance
<script type="application/ld+json">
{
"name":"<?php ($data[restaurant_name]);?>"
"author": {
"#type": "<?php.....?>",
"name": "<?php.....?>"
},
"datePublished": "<?php ($data[date]);?>",
"description": "<?php ($data[description]);?>",
}
</script>
Do not construct JSON objects like this, it's error-prone!
just using PHP construct an associative array, then use json_encode() function to create valid JSON object and pass whole to JS.
// variables
$name = 'Foo';
$type = 'bar';
$authorName = 'John';
// array
$data = [
'name' => $name,
'author' => [
'#type' => $type,
'name' => $authorName
]
];
// encode to JSON and display
echo json_encode($data);

get error when json_decode string from ajax post

I try send string to controller, the string is json format, when send to controller, i get error and can't decode my json string in that controller. I try to encode first in my controller, but still get error. And the error is
"json_decode() expects parameter 1 to be string, array given",
exception: "ErrorException",
here in my json string
"{ "data" :
[{
"id": "TNI01",
"jenis_bayar": "TUNAI",
"no_kartu": "kosong",
"nominal": "10000",
"seq": "1"
} ,
{
"id": "DEB01",
"jenis_bayar": "DEBIT BCA",
"no_kartu": "786382432432",
"nominal": "20000",
"seq": "2"
}]
}"
here the controller
public function ArrayPostToTablePembayaran(Request $request)
{
$data = json_decode($request->datajson, true);
foreach ($data->data as $datas)
{
$id = $datas->id;
$jenisbayar = $datas->jenis_bayar;
$nokartu = "";
if($datas->no_kartu == "kosong")
{
$nokartu ="";
}
$nominal = $datas->nominal;
$seq = $data->seq;
$this->PosToTablePembayaran1($id , $jenisbayar , $nokartu , $nominal , $seq);
}
}
and here the ajax script for parse json string to controller
function PembayaranKeDatabase1(arraystring)
{
$.ajax(
{
type : "POST",
url : "{{ url('/trx_bayar') }}",
data : { datajson : JSON.parse(arraydata) } ,
dataType: "json",
success: function(data){
},
error: function() {
}
});
}
thanks before
The main issue in your code that you try to decode json twice: in client js code and on server.
Let's inspect what you do:
JS function PembayaranKeDatabase1(arraystring) has an argument of type string, I presume. I also presume that arraystring is a JSON-string. So, you decode JSON-string to object with
JSON.parse(arraydata)
// btw shouldn't it be
//JSON.parse(arraystring)
So, here you send some plain object to server, not json.
Next, on server you try to decode again. But you receive an array in $request->datajson, as json is already decoded on client-side.
So, you can choose between two options:
Remove JSON.parse:
data : { datajson : arraydata },
and use json_decode on server.
Remove json_decode($request->datajson, true) on server. Iterate over your data as
// as $request->datajson is an array
foreach ($request->datajson['data'] as $datas) {
// use [] notation as you work with array, not object
echo $datas['id'];
}

Uncaught TypeError: b.toLowerCase is not a function

I am fetching some records :
$companies = \App\User::where('type', 'pet-salon')->orWhere('type', 'veterinarian')->get();
return response()->json($companies);
The data coming back is an array of objects:
[{
id: 2,
type: "xxx",
deactivate: 0,
xxx: "Hello",
middle_name: "Mid",
lastname: "xxx",
//...
}]
This is the jQuery typeahead code:
$('#getCompaniesForConnection').typeahead({
source: function (query, process) {
return $.get('/all/companies', { query: query }, function (data) {
return process(data);
});
}
});
The exception its giving me :
Uncaught TypeError: b.toLowerCase is not a function
And the results drop-down is not showing too, What am i missing here ?
Yes, you need to json_encode your companies.
$companies = \App\User::where('type', 'pet-salon')->orWhere('type',
'veterinarian')->get();
$result = json_encode($companies ); // return this or echo
First, the PHP code looks like it's a laravel code, so you can just return the $companies variable like so:
$companies = \App\User::where('type', 'pet-salon')->orWhere('type', 'veterinarian')->get();
return $companies;
Since models and collections are converted to JSON when cast to a string, you can return Eloquent objects directly from your application's routes or controllers.
And also, let's see the definition of the process function to be sure that's not where the error is coming from.

Can't access JSON Object no matter what i'm trying

So i have this JSON Structure, which i want to access:
data { payload: "{"state":{"reported":{"measuredata":{…
JSON.parse doesnt work, neither does JSON.stringify.
i only can access payload, if i go any further, i receive error or undefined:
data.payload // works
data.payload["state"] //undefined
data.payload.state // undefined
data.payload[0].state // undefined
data.payload[0]["state"] // undefined
what am i doing wrong?
the thing that i can see is that you have a bad format on your json data { payload: "{"state":{"reported":{"measuredata":{…
it hspuld be witouth the double quote that be after the word payload payload: "{"state"
you have to have something like this
payload: {"state"
You just need to use JSON.parse for payload json string value.
JSON.parse(data.payload).state;
Sample code for parsing.
var data = {
"logged_in":true,
"town":"Dublin",
"state":"Ohio",
"country":"USA",
"products":
{
"pic_id":"1500",
"description":"Picture of a computer",
"localion":"img.cloudimages.us/2012/06/02/computer.jpg",
"type":"jpg",
"childrenimages":
{
"pic_id":"15011",
"description":"Picture of a cpu",
"localion":"img.cloudimages.us/2012/06/02/mycpu.png",
"type":"png"
}
}
};
var data1 = JSON.stringify(data);
var data_final = JSON.parse(data1);
console.log(data_final.products.pic_id);

Cant access data from json

I'm having trouble with JSON. I made this in PHP and I'm sending it to my JavaScript, but I can't get the values.
[
{
"book":[
{
"dir":"extract\/pg1065.epub"
},
{
"dir":"extract\/pg1065.epub\/1065\/0.css"
},
{
"dir":"extract\/pg1065.epub\/1065\/1.css"
},
}
{
"book":[
{
"dir":"extract\/pg6130-images.epub"
},
{
"dir":"extract\/pg6130-images.epub\/6130\/0.css"
},
}
]
I'm trying to access it with
var obj = JSON.parse(result);
alert(obj.book[0].dir[1]);
Anyone have any ideas?
First you need to validate your json, i have validate your json it gives error.
In your json dIr is id.
You have defined 3 dir id for same object this may be error.
EDIT: I missed it but first comment explains your missing your closing square brackets for the book arrays. Add that in and your good to go. Validate the JSON first.
You don't need to do JSON.parse you can simply do
var data = <?php echo "Your generated JSON code"; ?>;
Worth a note you can create your data structure in PHP and then simply use json_encode, then you can be sure it will be valid JSON
var data = <?php echo json_encode($yourData); ?>;
You have output an array so to get the first object you will do something like
var firstObj = data[0];
To get the first dir of the first book
var firstDir = data[0]["book"][0]["dir"];
[
{
"book": [
{
"dir": "extract/pg6130-images.epub"
},
{
"dir": "extract/pg6130-images.epub/6130/0.css"
}
]
},
{
"book2": [
{
"dir": "extract/pg6130-images.epub"
},
{
"dir": "extract/pg6130-images.epub/6130/0.css"
}
]
}
]
Your JSON was not valid i used: http://jsonlint.com/ to sort it!
Now you should be able to acess the data fine.
The code shown in the question is not a valid JSON. There are missing closing square brackets for each of the book arrays and (thanks to #punund) a missing comma between array members. The correct JSON would be this:
[
{
"book":[
{
"dir":"extract\/pg1065.epub"
},
{
"dir":"extract\/pg1065.epub\/1065\/0.css"
},
{
"dir":"extract\/pg1065.epub\/1065\/1.css"
}
]
},
{
"book":[
{
"dir":"extract\/pg6130-images.epub"
},
{
"dir":"extract\/pg6130-images.epub\/6130\/0.css"
}
]
}
]
You should not normally be printing JSON directly, but instead creating a JSON object in PHP and then using json_encode function. The following PHP will produce valid JSON for your scenario:
<?php
$result = array(
(object)array("book" => array((object)array("dir" => "extract/pg1065.epub"),
(object)array("dir" => "extract/pg1065.epub/1065/0.css"),
(object)array("dir" => "extract/pg1065.epub/1065/1.css"))),
(object)array("book" => array((object)array("dir" => "extract/pg6130-images.epub"),
(object)array("dir" => "extract/pg6130-images.epub/6130/0.css")))
);
echo json_encode($result);
?>

Categories