Read a particular value of JSON - php

{
"success" : true,
"message" : "",
"result" : {
"uuid" : "e606d53"
}
}
I am trying to read UUID
$obj = json_decode($execResult, true);
print_r($obj);
$UniID = $obj["result"]["uuid"];
echo $UniID; ///result Blank

Given the JSON you included at the top of the question as input, the print_r statement will output this:
Array
(
[success] => 1
[message] =>
[result] => Array
(
[uuid] => e606d53
)
)
But you said, in a comment:
the output is the same as i posted before
The only way I can interpret this is that you mean the JSON you included at the top of the question is the result of the print_r statement.
This suggests that your JSON is double encoded.
i.e. that there was an associative array which was encoded as a JSON text. Then that JSON text was encoded as a JSON text.
Since it was encoded twice, you need to decode it twice:
<?php
$execResult = '"{\n \"success\" : true,\n \"message\" : \"\",\n \"result\" : {\n \"uuid\" : \"e606d53\"\n }\n}"';
print "Original JSON\n\n";
print_r($execResult);
$decode_1 = json_decode($execResult, true);
print "\n\nDecoded once\n\n";
print_r($decode_1);
$decode_2 = json_decode($decode_1, true);
print "\n\nDecoded twice\n\n";
print_r($decode_2);
print "\n\$decode_2[\"result\"][\"uuid\"]\n\n";
$UniID = $decode_2["result"]["uuid"];
echo $UniID; ///result Blank
?>
Which outputs:
Original JSON
"{\n \"success\" : true,\n \"message\" : \"\",\n \"result\" : {\n \"uuid\" : \"e606d53\"\n }\n}"
Decoded once
{
"success" : true,
"message" : "",
"result" : {
"uuid" : "e606d53"
}
}
Decoded twice
Array
(
[success] => 1
[message] =>
[result] => Array
(
[uuid] => e606d53
)
)
$decode_2["result"]["uuid"]
e606d53

You can give it a try. It should work fine for your code.
$obj = json_decode($execResult);
echo $obj->result->uuid;

Related

Python to PHP | String to Multidimensional Json Object To Array

I have a python script which returns an object as string. I call this python script with php and then print out the result with var_dump(json_decode($result)) and get this (this it the right object I want so my python code works properly I guess):
string(467) "{"userData": {"geburtsdatum": "PMS_2018-01-01", "anrede": "PMS_Herr", "ID": "1", "nachname": "PMS_Nachname1", "Test": {"tel": "PMS_Tel1", "postalOptIn": 0, "postal": "S3_Postal1", "email": "PMS_EMail1"}, "vorname": "PMS_Vorname1" }} "
So as you can see its a string on php side.
But how can I convert it to an object now and the create a multidimensional array from it in php?
If you need more information pls ask Ill add it.
I tried:
json_decode($result, true);
json_decode($result);
$response = (array) $result;
all I get is an Array with 1 Index and the whole Object as Value in it.
The Object gets generated like this on python side:
for message in consumer:
if message.key == str.encode(sys.argv[1]):
returnValue = message.value #this here is an byte obj from external system
consumer.close()
print(returnValue.decode("latin-1"))
Edit 2 and Solution
After long search I found out that the service I'm using (3d Party) returns the result from the python script with json_encode(). I removed that and now this code works:
$array = json_decode($response, TRUE);
return var_dump($array);
Since it is a string you can decode it like this:
$string = '{"userData": {"geburtsdatum": "PMS_2018-01-01", "anrede": "PMS_Herr", "ID": "1", "nachname": "PMS_Nachname1", "Test": {"tel": "PMS_Tel1", "postalOptIn": 0, "postal": "S3_Postal1", "email": "PMS_EMail1"}, "vorname": "PMS_Vorname1" }}';
print_r(json_decode($string, true));
Which returns an array:
Array
(
[userData] => Array
(
[geburtsdatum] => PMS_2018-01-01
[anrede] => PMS_Herr
[ID] => 1
[nachname] => PMS_Nachname1
[Test] => Array
(
[tel] => PMS_Tel1
[postalOptIn] => 0
[postal] => S3_Postal1
[email] => PMS_EMail1
)
[vorname] => PMS_Vorname1
)
)

I'm trying to decode json array to php but it's returning a blank page

I'm trying to decode json array to php array using json_decode, but it's displaying a blank page
Here's the json array
[["id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"],["id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"]]
Here's the code to decode json
$json = file_get_contents('http://localhost/example/index.php/destinations/json');
$data = json_decode($json,true);
$names = $data['result'];
echo "<pre>";
echo $names;
print_r($names);
Thanks
For obtaining proper JSON using json_decode() and json_encode() follow these guidelines:
json_decode() :
This function only works with UTF-8 encoded strings.
Returns the value encoded in json in appropriate PHP type. Values true, false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
The key and value must be enclosed in double quotes single quotes are not valid.
Your JSON:
[["id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"],["id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"]]
apears to be invalid. Arrays use [] while objects use {}.
This is an example of how a proper PHP array structure would look like prior to doing json_encode() (before sending):
// array structure in PHP to get proper JSON
Array ( [0] => Array ( [id] => 2 [name] => Sam Nju [photo] => 1510074080885.jpg [qty] => 10 [price] => 10000.00 ) [1] => Array ( [id] => 3 [name] => Daniel [photo] => 1510074047056.jpg [qty] => 0 [price] => 40000.00 ) )
which was obtained using the following:
json_decode('[{"id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"},{"id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"}]', true)
which would mean doing this:
$myArray = array();
$firstPerson = array();
$secondPerson = array();
$firstPerson['id'] = 2;
$firstPerson['name'] = "Sam Nju";
// ...
$secondPerson['id'] = 3;
$firstPerson['name'] = "Daniel";
// ...
array_push($myArray, $firstPerson);
array_push($myArray, $secondPerson);
// or $myArray[0] = $firstPerson; and $myArray[1] = $secondPerson;
While valid JSON would look like this:
{{"id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"},{"id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"}}
If you are getting the data from a database you might want to use something like this:
$result = mysqli_query($con, "SELECT .... // database query, $con is connection variable
$myArray = array();
while($row = mysqli_fetch_array($result))
{
$tempArray = array();
$tempArray['id'] = $row[0];
$tempArray['name'] = $row[1];
$tempArray['photo'] = $row[2];
// ...
array_push($myArray, $tempArray);
}
// use print_r($myArray); to test it out.
Although your code looks correct, your JSON data is invalid. Objects are enclosed by {}, not []. Replace the JSON with this, and it should work.
[
{
"id": "2",
"name": "Sam Nju",
"photo": "1510074080885.jpg",
"qty": "10",
"price": "10000.00"
},
{
"id": "3",
"name": "Daniel",
"photo": "1510074047056.jpg",
"qty": "0",
"price": "40000.00"
}
]
Also above answer already mentioned it:
Your JSON is invalid. You can check this e.g. with an JSON linter like https://jsonlint.com/
Plus, you're referencing names with $names = $data['result'];. However, in your provided JSON there is no array (or better object), with key "result".
You may look up your PHP's error log file to understand where the problem lies.

How to encode core data to JSON with no slash in Swift or Php

My php will return error if the JSON have "/n" and "/". I'm not sure I need to change my php code or my swift code.
my php code
$json = file_get_contents('php://input');
$obj = json_decode($json, true);
print_r($obj);
it look like fail to decode?
Array ( [0] => {"user":"1","accbooktype":"æµæ°´è´¦æœ¬","accbookname":"日常","accbookid":"1","category":"日常","cid":"U1L2B555"} )
Success output:
Array ( [0] => Array ( [cid] => 5 [accbookname] => test [accbooktype] => test [category] => test [user] => test ) )
This is my swift code. If change the code here. I need to know how to encode the core data to JSON with no slash, how?
//newdict is Core data
let jsonData = try JSONSerialization.data(withJSONObject: newdict, options: [.prettyPrinted])
//I tried this also but not worked
//let jsonEncoder = JSONEncoder()
//let jsonData = try jsonEncoder.encode(newdict)
let jsonString = String(data: jsonData, encoding: .utf8)
bookJSON.append(jsonString!)
print(bookJSON)
output:
["{\n \"cid\" : \"U1L2B1\",\n \"user\" : \"1\",\n \"accbooktype\" : \"流水账本\",\n \"accbookname\" : \"日常\",\n \"accbookid\" : \"1\",\n \"category\" : \"日常\"\n}"]
To this
[
{
"cid": "5",
"accbookname" : "test",
"accbooktype": "test",
"category": "test",
"user": "test"
}
]
You can try this
header('Content-Type: application/json');
$request = json_decode(file_get_contents('php://input'), true);
print_r($request);
you can also use type casting
$request = (array) json_decode(file_get_contents('php://input'), true);

preg_match from JSON string in PHP [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 6 years ago.
i am need preg_match this
"supportsUnlock" : true,
code json
{
"supportsUnlock" : true,
"options" : [ "email", "questions" ],
"account" : {
"name" : "a#hotmail.com"
},
"emailAddress" : "a•••••#hotmail.com",
"emailDomain" : "hotmail.com",
"rescueEmail" : false,
"forgotPasswordFlow" : true
}
first store json in $json varibale
after decode it.
$data = json_decode($json);
print_r($data);
Check result after get it value by array.
You can use json_decode() function for getting values from json.
Example:
<?php
$json = '{
"supportsUnlock" : true,
"options" : [ "email", "questions" ],
"account" : {
"name" : "a#hotmail.com"
},
"emailAddress" : "a•••••#hotmail.com",
"emailDomain" : "hotmail.com",
"rescueEmail" : false,
"forgotPasswordFlow" : true
}';
$decodeJson = json_decode($json,true);
echo "<pre>";
print_r($decodeJson);
echo $decodeJson['supportsUnlock']; // true
?>
Result of print_r():
Array
(
[supportsUnlock] => 1
[options] => Array
(
[0] => email
[1] => questions
)
[account] => Array
(
[name] => a#hotmail.com
)
[emailAddress] => a•••••#hotmail.com
[emailDomain] => hotmail.com
[rescueEmail] =>
[forgotPasswordFlow] => 1
)
Also note that, json_decode(string,true) will return result in array format if you need result in object than you can just remove the second param of TRUE.

PHP & JSON Decoding

I'm trying to decode some basic JSON data from Mintpal.com (https://www.mintpal.com/api)
The raw data looks like:
[
{
"market_id": "152",
"coin": "VeriCoin",
"code": "VRC",
"exchange": "BTC",
"last_price": "0.00008512",
"yesterday_price": "0.00009300",
"change": "-8.47",
"24hhigh": "0.00009450",
"24hlow": "0.00008050",
"24hvol": "13.153",
"top_bid": "0.00008063",
"top_ask": "0.00008591"
}
]
I just want to pull bits off this information out and assign them to variables. I use the below code with another near identical JSON output and it works fine.
//GET MINTPAL JSON DATA
$url = "https://api.mintpal.com/v1/market/stats/VRC/BTC";
$contents = file_get_contents($url);
$json = json_decode($contents);
//GET 'LAST BID' INFO
$lastBid = $json->code;
The previous raw JSON that works with the above code looks exactly the same, except for not being encased in '[...]' as the Mintpal one is.
{
"success": true,
"message": "",
"result": [
{
"MarketName": "BTC-LTC",
"High": 0.01126000,
"Low": 0.01060000,
"Volume": 442.30927821,
"Last": 0.01061100,
"BaseVolume": 4.86528601,
"TimeStamp": "2014-08-27T13:49:03.497",
"Bid": 0.01051801,
"Ask": 0.01061100,
"OpenBuyOrders": 50,
"OpenSellOrders": 116,
"PrevDay": 0.01079000,
"Created": "2014-02-13T00:00:00"
}
]
}
Any ideas on why I can't read the information this time round?
If you either did a var_dump() or a print_r() of your $json variable you should see that it is now an array starting at element 0 containing all the unique json elements.
//GET MINTPAL JSON DATA
$url = "https://api.mintpal.com/v1/market/stats/VRC/BTC";
$contents = file_get_contents($url);
$json = json_decode($contents);
pR($json);
//GET 'LAST BID' INFO
$lastBid = $json->code;
function pR($data){
echo "<pre>";
print_r($data);
echo "</pre>";
}
That yielded:
Array
(
[0] => stdClass Object
(
[market_id] => 152
[coin] => VeriCoin
[code] => VRC
[exchange] => BTC
[last_price] => 0.00008512
[yesterday_price] => 0.00009300
[change] => -8.47
[24hhigh] => 0.00009300
[24hlow] => 0.00008050
[24hvol] => 12.968
[top_bid] => 0.00008065
[top_ask] => 0.00008585
)
)

Categories