How to decode value from json, php - php

I need to decode the below json from a mobile app
Array
(
[{"unm":"admin","pw”:”password”}] =>
)
and my php code is
$obj1 = print_r($_REQUEST, true); //get $_request variable data(responce of login) data as it is
foreach($obj1 as $key => $value)
{
$obj2 = $key; //get first key
}
$obj3 = json_decode($obj2); //decode json data to obj3
$mob_user_name = $obj2['unm']; //getting json username field value
$mob_user_password = $obj2['pw']; //getting json password field value

Hope this will fix your issue,
Note: content is nothing but which you have received from iOS app
content = Array (
[{"unm":"admin","pw”:”password”}] => )
parse that in php
$json = json_decode($content, true);
print json[0]['unm']; /* prints the username */
print json[0]['pw']; /* prints the password */

{"unm":"admin","pw”:”password”} is an object, and json_decode() will by default build it as so.
$obj = json_decode('{"unm":"admin","pw”:”password”}');
echo $obj->unm;
echo $obj->pw;
If for some reason you want it to be converted to an associative array, set the second parameter of json_decode() to true as specified in the manual.
$arr = json_decode('{"unm":"admin","pw”:”password”}', true);
echo $arr['unm'];
echo $arr['pw'];

Related

Adding object to array also adds 'null'

I send the following data to my php file via ajax:
JSON.stringify({test1: '1', test2: '2'})
I would like to write this data to my JSON FILE content.json containing an empty array
[]
I only want to add the content though if it is not there, yet. This is my PHP code:
$jsonStringObject = file_get_contents("php://input");
$phpObject = json_decode($jsonStringObject);
$newJsonStringObject = json_encode($phpObject);
header('Content-Type: application/json');
$jsonString = file_get_contents('content.json');
$data = (array) json_decode($jsonString, true);
if (in_array($phpObject, $data) === false){
$data[] = $phpObject;
}
$newJsonString = json_encode($data);
file_put_contents('content.json', $newJsonString);
It almost works. Something is wrong with the way the data is added to the array because when I call the function for the first time, it updates content.json to
[null,{"test1":"1","test2":"2"}]
On calling the function again, it adds the object again despite the if-statement:
[null,{"test1":"1","test2":"2"},{"test1":"1","test2":"2"},{"test1":"1","test2":"2"}]
Can anyone help me to spot the mistake?
You're comparing apples and oranges (or rather objects to arrays).
Make sure you decode all json as arrays:
$jsonStringObject = file_get_contents("php://input");
// Added true as second argument to get it bas as an array
$phpObject = json_decode($jsonStringObject, true);
$jsonString = file_get_contents('content.json');
// Removed the (array) since the second argument literally means "return as array"
$data = json_decode($jsonString, true);
if (in_array($phpObject, $data) === false){
$data[] = $phpObject;
}
$newJsonString = json_encode($data);
file_put_contents('content.json', $newJsonString);
Demo: https://3v4l.org/rnCn5

.JSON file creates NULL value via PHP

So I'm trying to figure out why I get a NULL value in my .json file after I try to write the array to it. It only happens with the 'array_push' line after creating a new file. If there is a .json file already there with a value in it, it'll write to it correctly. The only thing I could guess was the file is missing the '{' and '}' in it upon creation.
I've got a small work around so far, but not sure that this is the right way to do it. Can someone tell me if this is good or bad?
Just to clarify, the .json document only holds the vault of NULL, there are no array elements or anything in the file besides the word NULL.
//CHECK IF FILE EXISTS, ELSE CREATE IT
$log_filename = "./site_files/logs/error-404-log.json";
if(!file_exists($log_filename)) {
touch($log_filename);
//LINE BELOW IS MY WORK AROUND, I'M NOT SURE IF THIS IS THE RIGHT WAY
file_put_contents($log_filename, json_encode(json_decode("{}")));
echo "$log_filename was created. <br />";
}
$log_array = array();
$new_data = array(
'current_date_stamp' => $current_date_stamp,
'current_page_trail' => $current_page_trail
);
$json_data = file_get_contents($log_filename);
if($log_array != "") { $log_array = json_decode($json_data, true); }
//WHEN CREATING A NEW FILE, ARRAY_PUSH GIVES ERROR
array_push($log_array, $new_data);
$json_data = json_encode($log_array, JSON_PRETTY_PRINT);
file_put_contents($log_filename, $json_data);
$log_filename = "error-404-log.json"; // establish the path/to/filename.json
if (file_exists($log_filename)) { // if path/to/filename.json exists
$json = file_get_contents($log_filename); // access PRETTY json string
echo "pre-existing data: <div><pre>$json</pre></div><br>"; // display json string
$array = json_decode($json, true); // decode to prepare for new data
}
// data always maintains the same structure: an array of 2-element arrays
$array[] = [
'current_date_stamp' => date('Y-m-d H:i:s'),
'current_page_trail' => "foo"
];
// create/update the file
$new_json = json_encode($array, JSON_PRETTY_PRINT); // re-encode updated array data
echo "new data: <div><pre>$new_json</pre></div>"; // display new json string
file_put_contents($log_filename, $new_json); // create or overwrite file
Your code is failing because you are comparing $log_array with an empty string, this condition will always pass because this array will never be an empty string. In the if statement you decode the contents of the file, when the file has no content this will be an empty string and it will return NULL, after this you write this NULL value to your file. If you check if $json_data is an empty string your code should work, I would also recommend doing it like this:
$log_array = array();
$new_data = array(
'current_date_stamp' => $current_date_stamp,
'current_page_trail' => $current_page_trail
);
$json_data = file_get_contents($log_filename);
if($json_data != "") {
$log_array = json_decode($json_data, true);
//WHEN CREATING A NEW FILE, ARRAY_PUSH GIVES ERROR
array_push($log_array, $new_data);
$json_data = json_encode($log_array, JSON_PRETTY_PRINT);
file_put_contents($log_filename, $json_data);
}
This is better since if the string is empty all other actions are irrelevant.

trying to use json_decode but it keeps returning a string instad of a object

I'm trying to access the information in a JSON string by using json_decode,
but it is returning a string instead of a object. My code
var_dump(json_decode($json)); // print json object to make sure it is working
$obj = json_decode($json); // get json object
print $obj->{'time'}; // 12345 // error because obj is a string
Try this below one instead of $obj = json_decode($json)
$obj = json_decode($json,true);
Ex:
$obj = '{"name":"vijay","age":27,"city":"New York"}';
$obj = json_decode($obj,true);
echo $obj["name"]; // vijay

How to access specific value in php and json

I'm using a token:
$url = "https://api.pipedrive.com/v1/deals?api_token=3bd884bb0078f836a56f1464097fb71eac9d50ce";
and here's the json text(not everything);
{
"success":true,
"data":[{
"id":1,
"creator_user_id":{
"id":1682756,
"name":"Kamilah",
"email":"kamilah#fractal.ae",
"has_pic":false,
"pic_hash":null,
"active_flag":true,
"value":1682756},
"title":"FFS Organization deal"
}]
}
I wanted to display "title" and I always get an error
Notice: Undefined index: creator_user_id in
C:\xampp\htdocs\pipedrive\getjson.php on line 8
Here's my code so far:
$url = "https://api.pipedrive.com/v1/deals?api_token=3bd884bb0078f836a56f1464097fb71eac9d50ce";
$response = file_get_contents($url);
$object = json_decode($response, true);
echo $object['data']['creator_user_id']['title'];
I'm new to json so I'm just practicing and trying to figure out how to echo a specific value in php. Would be appreciated if you can explain exactly how it works when you echo from json to php.
Thank you! :)
First of all you need to debug the array after using json_decode().
<?php
$url = "https://api.pipedrive.com/v1/deals?api_token=3bd884bb0078f836a56f1464097fb71eac9d50ce";
$response = file_get_contents($url);
$object = json_decode($response, true);
echo "<pre>";
print_r($object); // this will print all data into array format.
?>
As per this array, you do not have title index inside the creator_user_id array. title is a separate index.
Also note that, $object['data'] containing two indexes not one. you can get title as:
<?php
foreach ($object['data'] as $key => $value) {
//print_r($value); // this will print the values inside the data array.
echo $value['title']."<br/>"; // this will print all title inside your array.
}
?>
Result:
FFS Organization deal
Google deal

Json api decoding

here is my json
{
"rgInventory": {
"5455029633": {
"id":"5455029633",
"classid":"310776543",
"instanceid":"302028390",
"amount":"1"
}
}
}
Here is my way to parse json in php
$content = file_get_contents("http://steamcommunity.com/profiles/76561198201055225/inventory/json/730/2");
$decode = json_decode($content);
foreach($decode->rgInventory->5455029633 as $appid){
echo $appid->id;
}
I need to get that 5455029633 but it dont work in foreach.
And I want to store it in the variable too.
Json, which you've provided is invalid. Remove last comma from "amount":"1", and you are missing closing curly bracket. Then you should be able to access desired value as $decode->rgInventory->{"5455029633"}.
Or make your life simpler ;) and just go for assoc array $decode = json_decode($content, true);
You will need to pass true as second argument to the function json_decode to get an array instead of an object :
PHP
<?php
$content = file_get_contents("http://steamcommunity.com/profiles/76561198201055225/inventory/json/730/2");
$decode = json_decode($content, true);
echo $decode['rgInventory']['6255037137']['id']; // will output the property 'id' of the inventory 6255037137
$invetory = $decode['rgInventory']['6255037137'] // will store the inventory 6255037137 in the variable $inventory
?>

Categories