Getting the field of an object - php

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!

Related

Use json_encode() for JSON representation of a value in php file

I need help to properly use json_encode() to return a JSON representation of a value in my php server script. As far as i learned, this is not done with echo, print or loop as explained in all the other questions i studied before asking.
How do i get one "Value" from my data.json file
{
"clientPrivateKey": {
"Name":"AWS_CLIENT_SECRET_KEY",
"Value":"someexammplestring"
},
"serverPublicKey": {
"Name":"AWS_SERVER_PUBLIC_KEY",
"Value":"someexammplestring"
},
"serverPrivateKey": {
"Name":"AWS_SERVER_PRIVATE_KEY",
"Value":"someexammplestring"
},
"expectedBucketName": {
"Name":"S3_BUCKET_NAME",
"Value":"someexammplestring"
}
}
into the corresponding PHP variable in my php server script?
$clientPrivateKey =
$serverPublicKey =
$serverPrivateKey =
$expectedBucketName =
I only need the "Value" string here. The value is supposed to give a valid JSON response inside the php server script calculating signatures or else it will {"invalid":true}. Thanx for your help!
To get the data from a JSON file, you use json_decode(), not json_encode(). Then you access the parts of it using normal PHP object syntax.
$json = file_get_contents("data.json");
$data = json_decode($json);
$clientPrivateKey = $data->clientPrivateKey->Value;
$serverPublicKey = $data->serverPublicKey->Value;
$serverPrivateKey = $data->serverPrivateKey->Value;
$expectedBucketName = $data->expectedBucketName->Value;
1. You need to decode your JSON to make it usable:
$json = json_decode($jsonString, true);
Note the second parameter set to 'true', it means that we want an associative array instead of an object.
2. You can now use your JSON as a regular associative array:
$clientPrivateKey = $json['clientPrivateKey']['Value'];
You can access the two others values you want by following the previous example.
If you want to know if the offset is valid you can use the isset() function on it.
You need to use json_decode() like so:
$json = json_decode({
"clientPrivateKey": {
"Name":"AWS_CLIENT_SECRET_KEY",
"Value":"someexammplestring"
},
"serverPublicKey": {
"Name":"AWS_SERVER_PUBLIC_KEY",
"Value":"someexammplestring"
},
"serverPrivateKey": {
"Name":"AWS_SERVER_PRIVATE_KEY",
"Value":"someexammplestring"
},
"expectedBucketName": {
"Name":"S3_BUCKET_NAME",
"Value":"someexammplestring"
}
},true);
$clientPrivateKey = $json['clientPrivateKey']['Value'];
$serverPublicKey = $json['serverPublicKey']['Value'];
$serverPrivateKey = $json['serverPrivateKey']['Value'];
$expectedBucketName = $json['expectedBucketName']['Value'];
There you go:
<?php
$json = json_decode(file_get_contents('data.json'));
$clientPrivateKey = $json->clientPrivateKey->Value;
// ...
You can use this one liner to code to automatically extract the variables from an array:
extract(array_combine(array_keys($array=json_decode($json,true)),array_column($array,"Value")));
// $clientPrivateKey,$serverPublicKey,$serverPrivateKey,$expectedBucketName are now set
Example: http://sandbox.onlinephpfunctions.com/code/8f1de6493c35cadd0976532b36a23c2fb09bc7b2

JSON parsing - outputs NULL - PHP

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.

How to correctly send data to json via php?

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

JSON: How to check schema in PHP

I am a newbie. I am trying to make some experience about REST applications in PHP. So I receive (POST) a JSON body and store the value in my database. I just want to make a check if the JSON body I get is in the right way, if it matches the particular schema I set. I need something like this (for example):
my schema:
{"id":"int",
"name":"string",
"value":"double"
}
I just want to check that my JSON body contains the same fields and types. Thanks in advance.
UPDATE
Thanks to all for your answers. I'd like to follow krichprollsch's answer. It's exactly what I need. So I am using Ubuntu 12.04 LTS and NGINX server. I only installed HttpFoundation and Validator components via Composer. Now in my "www" folder I have a folder called "vendor" where Symfony's components are (I don't know if this folder has to be there). In order to check I made a script taken from some examples on the web but I've got a "500 Internal Server Error". The script is this:
<?php
require 'vendor/autoload.php';
use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints\Lenght;
class user{
public function utente(){
$validator = Validation::createValidator();
$violations = $validator->validateValue('Bernhard', new Lenght(array('min'=>10)));
echo $violations;
}
}
$a = new user;
$a->utente();
?>
Any suggestions? Thanks
You can use the Symfony Validator component to validate the data from the json according with your schema : http://symfony.com/doc/master/book/validation.html
<?php
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Validation;
//...
$collectionConstraint = new Assert\Collection(
array(
'id' => new Assert\Type(array('type'=>'integer')),
'name' => new Assert\Type(array('type'=>'string')),
'value' => new Assert\Type(array('type'=>'double'))
)
);
//...
$data = json_decode($your_json);
$validator = Validation::createValidator();
$errorList = $validator->validateValue($data, $collectionConstraint);
Using Symfony validator allow you to check complex constraints, not only type of data.
You can also directly validate an hydrated object. Useful if you want to insert into database.
You want chek value???
YOu can decode json strings with json_decode() function.
For example:
$json = {"id":"int",
"name":"string",
"value":"double"
};
$decode = json_decode($json);
if($decode->value == 'Your value') {
//your code
} else {
echo 'Incorerct!';
}
Hey You can decode you json by php
using json_decode function
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$array1 = json_decode($json, true);// it will return an array
for more about json_decode http://in2.php.net/json_decode
and can compare your data structure array ($array2) with this array
by intersecting them.
$result = array_intersect($array1, $array2);
print_r($result);
You can use json_decode to check if it is a valid syntax
$json = '{"id":"int",
"name":"string",
"value":"double"
}';
$decoded = json_decode($json, true);
if($decoded == null){
//your error message
echo "Error in JSON Format";
}
if the string is not valid, json_decode will return a null value

select a node from json string

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.

Categories