Converting JSON string to Associative array in PHP - php

What I'm trying to Do is so simple yet everything I tries had failed. I have the following string: "{"msg":"background1.jpg"}", and I want to convert it to an array to access the msg value. this should simply be done like so(or so I've thought):
$theString = "{"msg":"background1.jpg"}";
var_dump(json_decode($theString, TRUE));
The vr_dump() is dumping NULL, also tried:
var_dump(json_decode(json_encode($theString), TRUE));
This dumps string(45) "{"msg":"background1.jpg"}"
and tried many many more things, but all failed. Any thought please.
EDIT:
I'm getting the json string from database, where i have previously stored like so:
$toBeStored = json_encode(array("msg" => $value));

Try this
$var = '{"msg": "background1.jpg"}';
var_dump($var);
`

Related

PHP check JSON string for item = value

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)

At a loss with JSON, PHP, AS3: Cannot trace correct value

I have used JSON objects before and they work perfectly but the JSON objects that I made before have been from a result of fetched MySQL entries. Now, I am trying to make my own JSON object through an array in PHP and it shows correctly in the database but I cannot access any of the values like before.
$chatArray = array(
array(
'chatusername' => 'Troy',
'chatuserid' => '123',
'chatmessage' => 'Hello World'
),
array(
'chatusername' => 'Nick',
'chatuserid' => '124',
'chatmessage' => 'Testing'
));
$inputArray = json_encode($chatArray);
That is what I input into my database and like I said it works good. Then I call for it in a separate .php and get this
{"chat":"[{\"chatuserid\": \"123\", \"chatmessage\": \"Hello World\", \"chatusername\": \"Troy\"}, {\"chatuserid\": \"124\", \"chatmessage\": \"Testing\", \"chatusername\": \"Nick\"}]"}
It throws the "chat" out front which is the column name in my database which I am not sure why.
When I trace it I can only seem to trace it by
var messageArray:Object = JSON.parse(event.target.data);
trace(messageArray.chat);
Any time I try to reference say messageArray.chat.chatusername it returns an error.
I'm sorry I know it is probably a simple solution but I have been searching and working at it for a few hours now.
Any help is much appreciated! Thank you!
From the PHP code that generates your JSON output:
$stmt = $conn->prepare("SELECT chat FROM markerinfo WHERE markerid='$chatid'");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($result);
Keep in mind that the chat column in your database contains a JSON-string.
This code is not decoding the JSON-string in your database, so $result will be an array containing a JSON-string as well:
$result = [
'chat' => '[{"chatusername":"Troy","chatuserid":"123","chatmessage":"Hello World"},{"chatusername":"Nick","chatuserid":"124","chatmessage":"Testing"}]'
];
By passing that array through json_encode(), you're double-encoding your JSON-string.
For your purposes, you can probably get away with:
echo $result['chat'];
But, if you want the chat column name to be included in your output, you will have to decode the stored JSON first:
$result['chat'] = json_decode($result['chat']);
echo json_encode($result);
Probably this is related to the php side when it encodes your array, it will escape it with slashes, and this confuses the JSON parsing in your JS side. Try to add the JSON_UNESCAPED_SLASHES option to your json_encode function like this:
$inputArray = json_encode($chatArray, JSON_UNESCAPED_SLASHES);
Check the json_encode function documentation for more details:
http://php.net/manual/en/function.json-encode.php

get data from json array in php

I am having trouble accessing information in a json-Array that I retrieved using php's json_decode function.
the json-file looks as follows:
{"code":0,"message":"Okay","model":{"results":[{"message":"Okay","balance":0,"openPositions":[[],[]],"firstDepositDate":XXX,"currencySign":"€","email":"X.X#X.com","code":0}]},"result":"success"}
I used the following php code to get the contents:
$json = file_get_contents($json_url);
$data = json_decode($json,true);
echo '<pre>' . print_r($json, true) . '</pre>';
The result print_r displays looks just like what I expect and looks like the json.
However, I cannot figure out to access the variables. Whenever I try something like
$test = $json['model']['results']['balance'];
the script throws an error, which I can't identify. I already figured out if I access the $json variable like so:
$test = $json[n]; // returns the nth character, e.g. n = 0 $test = "{", n = 2 $test = "c"
The script also did not throw an error if I tried accessing the variable like so:
$test = $json['code']; // returns "{"
Can someone help me figure out how to navigate this array?
Thanks!
The results key is a true array, not an unordered map (key/value). Additionally, you should be accessing the decoded $data, not the $json string.
This should work for you:
$test = $data['model']['results'][0]['balance'];
This is what should have tipped you off:
{"results":[{"message"
^ ^
| |
| \-- Start of an array
|
\-- Start of an object
You recieve an error similar to Cannot use object of type stdClass as array in (...) right?
json_decode returns an object of the type stdClass which is the only object in php (as far as I know) which properties cannot be accessed like an array. You will have to access them as follows:
$json = '{"code":0,"message":"Okay","model":{"results":[{"message":"Okay","balance":0,"openPositions":[[],[]],"firstDepositDate":"XX","currencySign":"€","email":"X.X#X.com","code":0}]},"result":"success"}';
$obj = json_decode($json);
var_dump($obj->message); //works
var_dump($obj["message"]); //throws exception
There is an error in the JSON array. "firstDepositDate": XXX is not a valid value. Should be a string "XXX".
Also you are trying to the wrong variable. The decoded data should be a PHP array. In this case $data['code'] instead of $json['code']

how to use JSON.stringify and json_decode() properly

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

Help Decoding JSON

I'm trying to get the "screenshotUrls" string from this piece of json:
$request_url = 'http://itunes.apple.com/search?term=ibooks&country=us&entity=software&limit=1';
$json = file_get_contents($request_url);
$decode = json_decode($json, true);
echo $decode['results'][0]['screenshotUrls'];
But I get only text "Array"
What have I done wrong?
Try
var_dump($decode['results'][0]['screenshotUrls']);
IF you get 'Array' output by PHP that means that you're trying to echo an actual array (or the string 'Array'...). That means you need to get a specific index value.
Since $decode['results']['0']['screenshotUrls'] is an array, if you want just a string (say, delimited by commas), you could use
echo implode(",", $decode['results']['0']['screenshotUrls']);
This will iterate over the array, and return a comma-separated string of all the URLs.
Do a var_dump($decode['results']['0']['screenshotUrls']). You'll find that the ['screenshotUrls'] is actually an Array, containing one or more URLs (hence the plural 'urls' in its name).
There's nothing wrong with your code so far, but $decode['results'][0]['screenshotUrls'] is an array of all the URLs to screenshots. To go through each one individualy, you need to do:
forearch ($decode['results'][0]['screenshotUrls'] as $url) {
// Do stuff here
}

Categories