I am querying a 3rd party service which outputs json.
$data = json_decode($result,true);
var_dump ($data);
$data holds this:
{"response":{"status":"OK","token":"hbapi:187089:586e655ed1f9c:nym2","dbg_info":{"instance":"53.bm-hbapi.prod.ams1","slave_hit":false,"db":"master","parent_dbg_info":{"instance":"64.bm-hbapi.prod.nym2","slave_hit":false,"db":"master","parent_dbg_info":{"instance":"45.bm-api.prod.nym2","slave_hit":false,"db":"master","time":664.07299041748,"version":"1.17","warnings":[],"slave_lag":0,"start_microtime":1483629917.8571},"awesomesauce_cache_used":false,"count_cache_used":false,"uuid":"39e1c17a-7fe4-58ac-9486-c4dd5bbf96a3","warnings":[],"time":1159.7349643707,"start_microtime":1483629917.7835,"version":"1.17.150","slave_lag":0,"output_term":"not_found"},"awesomesauce_cache_used":false,"count_cache_used":false,"uuid":"286ca4bc-6964-50ad-b241-ff9df1304278","warnings":[],"time":1347.2578525543,"start_microtime":1483629917.6534,"version":"1.17.150","slave_lag":0,"output_term":"not_found","master_instance":"64.bm-hbapi.prod.nym2","proxy":true,"master_time":1159.7349643707}}}
I am trying to get the token value.
I tried
$token = $data["response"][0]["token"];
I get NULL
I also tried
$token = $data['response'][0]['token'];
And I still get NULL.
I have looked at How can I access an array/object? and other threads - can't find the issue.
$token = $data["response"]["token"];
json:
{
"response": {
"status": "OK",
"token": "hbapi:187089:586e655ed1f9c:nym2",
"dbg_info": {
}
}
}
Why are you accessing the pos [0] if isn't an array?
Instead of that try to access to the desired parameter like this:
$token = $data["response"]["token"];
change $data['response'][0]['token']; to $data['response']['token'];
$data['response'] is, it doesnot have the 0 index.
{
"status": "OK",
"token": "hbapi:187089:586e655ed1f9c:nym2",
"dbg_info": {
}
$data is an object (not an array), so you can access response as a property of this object: $data->response.
response is again an object. etc..
For example status can be called like this: $data->response->status.
You can see what is an object and what is an array using this code:
print "<pre>";
var_dump($data);
So in your case, to get token:
$token = $data->response->token
In $data you still have json, so you should call json_decode($data) one more time.
Related
When I make a request to my webservice one time I get:
funcion login returns => {
"token":"fsuehfisubfibiefasasdapmwineq","client":"Admin","permission":"ADMIN"
}
And I can just save something like the client or the token in a variable, doing for example:
$json = login($email,$password); - saving the JSON in the variable $json.
$values = json_decode($json); - decoding the $json and saving it on $values.
And know if I want to save the name or the token for future requests to the webservice I make a variable:
$token = $values->{'token'};
$client = $values->{'client'};
But my question is what i do when i get this from the webservice, because I did the same and tried somethings and I'm not getting anywhere.
funcion member returns = {
"Table":[
{
"client":"Admin",
"name":"Martin Lupin",
"age":"25",
"city":"Lisbon"
}
]
}
How do I access to "client", "name", "age", "city"?
I tried to do:
$name = $valuesclient->{'client'}; - and nothing
$name = $valuesclient->{'table'}->{'client'}; - and nothing
$name = $valuesclient->{'table'->{'client'}}; - and nothing
Can someone help me?
I have objects like below
{
"user": "58a9bf92e0f78000055dd932",
"type": "template_created",
"count": 2
}
I need to get 'user' field, ..->type returns "template_created" and ..->count gives its value but ..->user returns null. These objects come from mongodb aggregation framework by the way.
Use this code
$data = json_decode($data); //where $data contain the json
$data->user;
It looks, like your objects are json-encoded. This means, you can use the native php functions json_encode() and json_decode() to process them. In your example, you can deserialize the object by calling
$obj = json_decode($str);
with $str being the data you show above. Now you can access the fields of this object with standard php access methods like
$type = $obj->type;
Hope this helps!
Don't forget to check errors after json_decode, like this:
$payload = json_decode($data);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException('Invalid JSON.');
}
// also you cah check this
if (property_exists($payload, 'user')) {
var_export($payload->user);
}
You can resolve with two ways :-
$data = '{
"user": "58a9bf92e0f78000055dd932",
"type": "template_created",
"count": 2
}';
$objectdata = json_decode($data); //stclassobject
echo $objectdata->count;
--------OR-------
$arraydata= json_decode($data,true); //convert to array
echo $arraydata['count'];
Hope it hepls!
I am working with Mailchimp API, and trying to pass the user name from my form to the list.
Mailchimp has a nested structure for an actual user name, and I don't understand how to correctly write code for it.
The JSON data structure looks like that:
{
"email_address": xxx#xxx.com
"merge_fields": {
"FNAME":
"LNAME":
}
}
To send the post request the script using a function with post method
$result = $MailChimp->post("lists/$mailchimp_list_id/members", [
'email_address' => $subscriber_email,
'status' => 'subscribed',
//'merge_fields'['FNAME'] => $subscriber_name;
]);
I try to send 'merge_fields'['FNAME'] => $subscriber_name;
Can anyone explain me how to get inside the JSON with PHP?
Try like this
$jsonArray = json_encode(array('0' =>'test','1' => 'test2'));
json_encode will convert your php array to json format
If you want to decode your json array to php array then use json_decode
$phpArray = json_decode('Any json encoded array');
Okay, this is the best way to work with JSONs in PHP:
Add this to get the full JSON Body:
$json = file_get_contents('php://input');
Validate the json. I work with the Respect Validator.
https://github.com/Respect/Validation/blob/master/docs/Json.md
if(v::json()->validate($json)){
$whatever = new whatever($json);
}
Normalize the json object with a php class
class whatever{
public $email;
public $merged_fields;
function __construct($json){
$json = json_decode($json);
if($json->email){
$this->email = $json->email
}else{
echo "Error";
}
}
}
Use jsonSerializable for encoding. This is a really good HowTo:
http://www.sitepoint.com/use-jsonserializable-interface/
First create a PHP data structure to match the required JSON structure and then json_encode() that structure.
The {} means object in JSON
The [] means array in JSON
<?php
$inner = new stdClass();
$inner->FNAME = $subscriber_first_name;
$inner->LNAME = $subscriber_last_name;
$member = new stdClass();
$member->email_address = 'xxx#xxx.com';
$member->merge_fields = $inner;
$json_string = json_encode($member);
I am trying to interpret the response from a web service call using json_decode. The JSON appears to be valid (have checked in online validators and such) but json_decode still returns NULL.
The data returned by the web service is as follows:
[{"id":"cc9dfabc36abc54c5a7","extension":"001","links":{"self":"https:\/\/someurl\/api\/response\/#me\/001\/cc9dfabc36abc54c5a7"}}]
The web service response data is stored in $result. My code to decode the JSON is as follows:
if (is_null(json_decode($result))){
$callObj = json_decode($result, true);
$callID = $callObj->extension;
}
else
{
echo "<BR>Could not decode response <BR>";
$callID = 'error';
}
return $callID;
Shouldn't the first test be negative (!is_null)? Only if it isn't null (and therefore a json object) should you then proceed.
Also, the second json_encode function you're passing a 'true' as the second argument which makes the returned object an associative array rather than an object.
The below alterations appeared to work for me.
if (!is_null(json_decode($result))){
$callObj = json_decode($result, true);
$callID = $callObj[0]['extension'];
}
else
{
echo "<BR>Could not decode response <BR>";
$callID = 'error';
}
return $callID;
I am trying to use the google translation API as shown on this page...
https://developers.google.com/translate/v2/using_rest
When I replace my API key, it works correctly and display the translated text as shown below.
GET https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&target=de&q=Hello%20world
{
"data": {
"translations": [
{
"translatedText": "Hallo Welt",
"detectedSourceLanguage": "en"
}
]
}
}
I will like to return only the text i.e. "Hallo Welt" using PHP.
I used json_decode function, but it returns everything.
$url = "https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&target=de&q=Hello%20world";
$data = file_get_contents($url);
$json = json_decode($data);
echo $json->data->translations[0]->translatedText;
$object = json_decode($yourJSONString);
echo $object->data->translations->translatedText;
Once you have used json_decode(), you just use the resulting object however you use any other PHP object.