I am currently working on a php/html/javascript project and am doing ajax post to a php script which returns json encoded data. Within this json encoded there is some more json encoded data.
Below is how I am json encoding the data
$category[0]['Category'] = "Category 1";
$category[1]['Category'] = "Category 2";
$article['Date'] = "11/11/2012 22:42:00";
$article['Title'] = "This is the title";
$article['Subtitle'] = "This is the subtitle";
$article['Content'] = "This is the content1";
$article['ViaName'] = "SomeSite";
$article['ViaAddress'] = "http://localhost";
$article['SourceName'] = "N/A";
$article['SourceAddress'] = "N/A";
$article['categories'] = json_encode($category);
echo json_encode($article);
The $article that gets json encoded I can access fine when it is returned to the javascript using json.Title, json.Subtitle etc.
But when I try and get the categories it doesn't work.
I've tried using json.categories and this prints out the following:
[{"Category":"Category 1"},{"Category":"Category 2"}]
This looks like its working so when I try and access each individual part it then doesn't work. I've tried json.categories[0].Category and json.categories.Category[0] but it keeps on coming up an undefined.
Thanks for any help you can provide.
If you encode an array with json_encode you got a string. So, in your case, json.categories is a string and not an array.
However, json_encode (and decode) is recursive.
So you should use simply
$article['categories'] = $category;
without encode again.
No wait. You are json encoding an array into a value of another array which will be encoded aswell. You should just do:
$article['categories'] = $category;
Add your category json array to article array to access with article variable
$article['categories'] = $category;
Related
I need to get the value one one particular value in my json string
the json string comes from an api url http://url:port/api.php?action=reg_user&sub=list and outputs like so
[{"id":"1","username":"username1","credits":"0","group_id":"1","group_name":"Administrators","last_login":"1511883014","date_registered":"1421604973","email":"test1#my-email.com","ip":"8.8.8.8","status":"1"},{"id":"31","username":"username2","credits":"0","group_id":"1","group_name":"Administrators","last_login":"1539813642","date_registered":"1473632400","email":"test2#my-email.com","ip":"8.8.8.8","status":"1"},
i would like to check the value of credits where username = username1
then if credits > 30 do x, else do y
I presume first of all I need to decode this jason string
so i tried to do
$api_result = file_get_contents( 'http://url:port/api.php?action=reg_user&sub=list' );
$json_decode = json_decode($api_result);
echo $json_decode;
expecting this to echo the array in a nicely formatted structure, instead it just outputs the word Array. Where do I go from here?
Thanks
UPDATE 1...
SO i checked again and I defo can echo $api_result so I know that the file_get_contents is working fine i tried the two comments suggestions however both didn't work...
one of the suggestions was to make my php
$api_result = file_get_contents( 'http://url:port/api.php?action=reg_user&sub=list' );
$json_decode = json_decode($api_result);
echo $json_decode['username'];
here is a screenshot of how the echo $api_result is formatted in case this isnt a propper json string
so to me this looks like it opens with (and is all contained in a pair of [] and then each result is enclosed in {} as I'd expect with a json string right? however i thought json strings used {} and arrays used {} so to me this looks like a string inside an array???
I looked at php.net's resource on JSON DECODE and tried var_dump(json_decode($json)); which did print me this
UPDATE 2
I just tried https://www.functions-online.com/json_decode.html and pasted the data in, it was able to decode the data absolutely fine,
It then gave me a copy if the json_decode sample at the bottom but this didn't work either, returning a null value like json_decode doesn't work on my server?
From your second screenshot (please cut & paste the text instead!) you can see the decoded JSON is an array of objects with properties id, username etc. So you can access them using object notation. This code uses the snippet of your api_result from your original question to demonstrate how to do what you want:
$api_result = '[{"id":"1","username":"username1","credits":"0","group_id":"1","group_name":"Administrators","last_login":"1511883014","date_registered":"1421604973","email":"test1#my-email.com","ip":"8.8.8.8","status":"1"},{"id":"31","username":"username2","credits":"0","group_id":"1","group_name":"Administrators","last_login":"1539813642","date_registered":"1473632400","email":"test2#my-email.com","ip":"8.8.8.8","status":"1"}]';
$json = json_decode($api_result);
foreach ($json as $user) {
if ($user->username == 'username1') {
if ($user->credits > 30) {
// do x
echo "user $user->username has more than 30 credits ($user->credits)";
}
else {
// do y
echo "user $user->username has less than or equal to 30 credits ($user->credits)";
}
}
}
Output:
user username1 has less than or equal to 30 credits (0)
I've got a database structure like this.
I'm willing to get row as a json object for Json.net.
My php code is this
$check_query = mysqli_query($conn, "select * from users where name = '$name' and password = '$pass'");
$rows = array();
while($r = mysqli_fetch_assoc($get_query)) {
$rows[] = $r;
}
if(count($rows) > 0) {
echo json_encode($rows[0]);
}
I'm getting json as this.
{"unique_id":"pcg9sy26","name":"w","password":"w","mail":"alpsavrum#gmail.com","age":18,"locale":"Turkey","city":"Istanbul","subscriptions":"[\"electronics\", \"vacations\"]","history":null,"token":"12562f39b990da0433d7be71992ed634"}
As you can see, subscriptions value is string. I need it to be array as it seems.
{"unique_id":"pcg9sy26","name":"w","password":"w","mail":"alpsavrum#gmail.com","age":18,"locale":"Turkey","city":"Istanbul","subscriptions":[\"electronics\", \"vacations\"],"history":null,"token":"12562f39b990da0433d7be71992ed634"}
Is there any way to achieve this. ?
Thanks a lot !
The way you're retrieving that data is giving you the JSON value as a string. Storing it as JSON in the database is a good idea if it's actually JSON data, but the mysqli driver will not automatically de-serialize it for you. If you want that sort of behaviour you'll need to use an ORM.
When you're having trouble with double encoding, check with var_dump to see what you're actually working with. That would reveal the subscriptions key contains a JSON string, not an array as expected.
What you'll have to do is manually de-serialize it prior to JSON encoding:
if (isset($r['subscriptions'])) {
$r['subscriptions'] = json_decode($r['subscriptions']);
}
$rows[] = $r;
You will need to do this for any and all JSON encoded fields your results might have.
This way you're JSON encoding a proper PHP data structure and not one that's part PHP and part JSON string.
Try json decode function in whatever language you are reading it.
Decode the JSON response and then print it
I've got a JSON object that I'm sending to a PHP script and I'm having trouble parsing the JSON. Here's the POST request:
http://mywebsite.com?action=somefunction&{%22id%22:1,%22Name%22:%22Mike%22}
And here's my PHP function, which obviously doesn't work:
$data = $_GET['data'];
$obj = json_decode($data);
echo $obj->Name;
die();
The end goal is to extract the name "Mike" from the URL string. Any suggestions?
Try taking a look at what PHP is outputting from json_decode():
$data = $_GET['data'];
$obj = json_decode($data);
var_dump($obj);
Your code itself works fine: http://ideone.com/0jsjgT
But your query string is missing the data= before the actual JSON. This:
http://mywebsite.com?action=somefunction&{%22id%22:1,%22Name%22:%22Mike%22}
should be this:
http://mywebsite.com?action=somefunction&data={%22id%22:1,%22Name%22:%22Mike%22}
you should do
echo $obj->{'Name'};
This also is a duplicate question of Echo data json by json_decode
Im trying to pass a mulitidimensional Javascript array to another page on my site by:
using JSON.stringify on the array
assigning the resultant value to an input field
posting that field to the second page
using json_decode on the posted value
then var_dump to test
(echo'ing the posted variable directly just to see if it came through
at all)
Javascript on page one:
var JSONstr = JSON.stringify(fullInfoArray);
document.getElementById('JSONfullInfoArray').value= JSONstr;
php on page two:
$data = json_decode($_POST["JSONfullInfoArray"]);
var_dump($data);
echo($_POST["JSONfullInfoArray"]);
The echo works fine but the var_dump returns NULL
What have I done wrong?
This got me fixed up:
$postedData = $_POST["JSONfullInfoArray"];
$tempData = str_replace("\\", "",$postedData);
$cleanData = json_decode($tempData);
var_dump($cleanData);
Im not sure why but the post was coming through with a bunch of "\" characters separating each variable in the string
Figured it out using json_last_error() as sugested by Bart which returned JSON_ERROR_SYNTAX
When you save some data using JSON.stringify() and then need to read that in php. The following code worked for me.
json_decode( html_entity_decode( stripslashes ($jsonString ) ) );
Thanks to #Thisguyhastwothumbs
When you use JSON stringify then use html_entity_decode first before json_decode.
$tempData = html_entity_decode($tempData);
$cleanData = json_decode($tempData);
You'll need to check the contents of $_POST["JSONfullInfoArray"]. If something doesn't parse json_decode will just return null. This isn't very helpful so when null is returned you should check json_last_error() to get more info on what went wrong.
None of the other answers worked in my case, most likely because the JSON array contained special characters. What fixed it for me:
Javascript (added encodeURIComponent)
var JSONstr = encodeURIComponent(JSON.stringify(fullInfoArray));
document.getElementById('JSONfullInfoArray').value = JSONstr;
PHP (unchanged from the question)
$data = json_decode($_POST["JSONfullInfoArray"]);
var_dump($data);
echo($_POST["JSONfullInfoArray"]);
Both echo and var_dump have been verified to work fine on a sample of more than 2000 user-entered datasets that included a URL field and a long text field, and that were returning NULL on var_dump for a subset that included URLs with the characters ?&#.
stripslashes(htmlspecialchars(JSON_DATA))
jsonText = $_REQUEST['myJSON'];
$decodedText = html_entity_decode($jsonText);
$myArray = json_decode($decodedText, true);`
I don't how this works, but it worked.
$post_data = json_decode(json_encode($_POST['request_key']));
If I have, in javascript, something like:
entriesObj1 = new Object();
entriesObj1.entryId = "abc";
entriesObj1.mediaType = 2;
entriesObj2 = new Object();
entriesObj2.entryId = "def";
entriesObj2.mediaType = 1;
var entries = new Array();
entries[0] = entriesObj1;
entries[1] = entriesObj2;
What is the best method to pass it to php through an HTTP POST?
I've tried a jQuery plugin to convert the array to JSON. I've tried to create multiple hidden fields named "entries[]", each one with the JSON string. Somehow, I can't seem to decode my data with PHP's json_decode.
EDIT:
I tried changing the JSON plugin used to the one #Michal indicated and the results I get are the same:
Javascript
[
{"disciplina":"sdfsdfsdfsd","titulo":"sdfsdfsdf","componentes":"Bloco Completo"},
{"disciplina":"sdfsdfsdfsd","titulo":"sdfsdfsdf","componentes":"Bloco Completo"}
]
PHP Vardump:
string(756) "
[
{\"disciplina\":\"sdfsdfsdfsd\",\"titulo\":\"sdfsdfsdf\",\"componentes\":\"Bloco Completo\"},
{\"disciplina\":\"sdfsdfsdfsd\",\"titulo\":\"sdfsdfsdf\",\"componentes\":\"Bloco Completo\"}
]
"
When I use PHP's json_decode, I get NULL.
var_dump(json_decode($_REQUEST['entries']));
Output:
NULL
You need to convert JSON to a string (use JSON stringifier (https://github.com/douglascrockford/JSON-js) and POST the string (as a field value) to the PHP script which does json_decode()
Concat it using some characters like _ or %% then pass it to PHP.
In PHP file:
$ar = array();
$ar = explode('special_char',string pass from js);
echo "pre";print_r($ar);
echo "/pre";
well, the trouble seemed to be with the quotes that were being passed in the post, so i just replaced the quotes with open strings to my $_REQUEST.