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.
Related
This question already has answers here:
How to add square braces around subarray data inside of a json encoded string?
(3 answers)
Closed 6 months ago.
this is the json i have to produce
{
"email": "example#example.com",
"campaign": {
"campaignId": "p86zQ"
},
"customFieldValues": [
{
"customFieldId": "y8jnp",
"value": ["18-29"]
}
]
}
if i use
$data = [
"email" => $_POST['mail'],
"campaign" => [
"campaignId" => "4JIXJ"
],
"customFieldValues" => [
"customFieldId" => "y8jnp",
"value" => ["18-29"]
]
];
and i do json_encode($data)
value is an object, but it should be an array with a single element. Somehow json_encode treats it as an object. Can i force it to treat it as an array with a single element ?
Thanks in Advance
Adrian
At the moment, you have a single array with 2 elements, instead of an array with a single element of a sub-array. In order to get the json in the first section, you need to add another array level.
$data = [
"email" => $_POST['mail'],
"campaign" => [
"campaignId" => "4JIXJ"
],
"customFieldValues" => [
[
"customFieldId" => "y8jnp",
"value" => ["18-29"]
]
]
];
That will give you this:
{
"email": null,
"campaign": {
"campaignId": "4JIXJ"
},
"customFieldValues": [
{
"customFieldId": "y8jnp",
"value": ["18-29"]
}
]
}
if there is one single element in the array the json_encode will treat is as an object and the key of the object is the index of the array
to treat it as an array you can use array_values(<your_array>)
{
"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;
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
I have a question about some JSON and PHP, see json below.
How can I get the number string?
{
”data”: [
{
”numbers”: [
{
”number”: "XXXX",
”type”: ””
}
]
}
]
}
Ive tried with the following but its not working:
$item['numbers'][0]->number;
Note, the $item array is ok. I just do not know what is wrong here.
EDIT:
I should point out that there was an json_decode before.
So the structure looks like this:
Array
(
[0] => Array
(
[number] => XXXX
[type] =>
)
)
print_r($item['numbers']);
This doesn't work: $item['numbers'][0]['number'];
Error: Undefined offset: 0 in
Thanks!
if you want to direct access then use this code
$items->data->numbers->number;
you can use php json_decode().it takes a JSON encoded string and converts it into a PHP variable.
<?php
$json_data = '{
"data": [
{
"numbers": [
{
"number": "11",
"Type": ""
}
]
}
]
}';
$array=json_decode($json_data,true);
echo "<pre>";
print_r($array);
echo $array["data"][0]["numbers"][0]["number"];
then output
Array
(
[data] => Array
(
[0] => Array
(
[numbers] => Array
(
[0] => Array
(
[number] => 11
[Type] =>
)
)
)
)
)
Number:11
To get the number try this :
$myJSON->data->numbers->number;
Hope this will help you out... You are trying to access which does not actually exists.
try this code snippet here
<?php
ini_set('display_errors', 1);
$month_options = '{
"data": [
{
"numbers": [
{
"number": "10",
"Type": ""
}
]
}
]
}';
$array=json_decode($month_options,true);
echo $array["data"][0]["numbers"][0]["number"];
Use the json_decode() function of PHP.
$array = json_decode('{
”data”: [
{
”numbers”: [
{
”number”: "",
”Type”: ””
}
]
}
]
}', true);
Then you could access it as $array["data"]["numbers"]["number"];
I have to convert form data to JSON format. I am trying to achieve this:-
{"appConfiguration" : {
"configuration_name" = "AS400 Configuration",
"configuration_version" = "1.001",
"connection" : [ {
"ip_address" : [ “10.10.10.01”,
“10.10.10.02”,
“10.10.10.03”
// all saved IP Address.
]
"port" : "23"
"ssl" : "NO",
"device_name" : "Agicent Device",
"name" : "Puga",
"user" : "smart gladiator",
"password" : "sgl2013",
"barcode_enter" : "NO",]}}
This is what my JSON should look like. I am able to store data in single-dimension array; how do I create a structure like this?
"connection":["ohiuh","ghu","ip_address":["something","something","something"]]
Try with this
$arr = array('connection'=>array("ohiuh","ghu" , json_encode(array("ip_address"=>array("something","something","something")))));
echo json_encode($arr);
To get for example ip_address you can do this:
$array = json_decode($jsonstring);
echo $array['connection']['ip_address']['something'];
This will decode your json string into an multidimensional array and than you can simply echo it.
To encode it:
$test = array("appConfiguration" => array("configuration_name"=> "AS400 Configuration", "configuration_version" => "1.001", "connection"=> array("ip_address" => array('10.10.10.01', '10.10.10.02', '10.10.10.03'), "port" => "23",
"ssl" => "NO",
"device_name" => "Agicent Device",
"name" => "Puga",
"user" => "smart gladiator",
"password" => "sgl2013",
"barcode_enter" => "NO")));
echo(json_encode($test));
To use data you get from a form you can do this:
$array = array('connection'=>array($_POST["ohiuh"],$_POST["ghu"] , array("ip_address"=>array($_POST["ip_adress1"],$_POST["ip_adress2"],$_POST["ip_adress3"])))));
echo json_encode($array);
Write a form with the value you need and than post them. Than create the array with the $_POST["something"] values and encode this array to json with json_encode();
Hope this is now the answer to your question.
I am trying to use a jQuery gantt as a wordpress plugin. Currently I'm stuck on editing the data.json. I use a php form to populate a new item. When submitting the form, it will add data to the file, but behind the closing square brackets.
[{
...
},
{ "name" : "Vermessung"
, "desc" : ""
, "values": [
{ "id" : "5"
, "from" : "/Date(1363132800000)/"
, "to" : "/Date(1368655200000)/"
, "desc" : "Vom Beauftragen der Vermessung bis zur tatsächlichen Vermessung"
, "customClass": "ganttBlue"
, "label" : "Vermessung"
}
]
}
]
After submitting the form it looks like this:
[{
...
},
{ "name" : "Vermessung"
, "desc" : ""
, "values": [
{ "id" : "5"
, "from" : "/Date(1363132800000)/"
, "to" : "/Date(1368655200000)/"
, "desc" : "Vom Beauftragen der Vermessung bis zur tatsächlichen Vermessung"
, "customClass": "ganttBlue"
, "label" : "Vermessung"
}
]
}
]{"name":null,"desc":null,"values":{"id":null,"from":null,"to":null,"desc":null,"customClass":null,"label":null}}
This is the requested php Code which will adding stuff to the json:
$file = jQg_BASENAME_DIR.'/inc/data.json';
log_me('This is a message for debugging purposes');
if(isset($_POST['submit'])){
$json = file_get_contents( $file );
$data = json_decode($json);
// convert form data to json format
$postArray = array(
"name" => $_POST['name'],
"desc" => $_POST['desc'],
"values" => array(
"id" => $_POST["value_id"],
"from" => $_POST['value_from'],
"to" => $_POST['value_to'],
"desc" => $_POST['value_desc'],
"customClass" => $_POST['value_class'],
"label" => $_POST['value_label']
)
); //you might need to process any other post fields you have..
$json = json_encode( $postArray );
array_push($json, $postArray);
// write to file
file_put_contents( $file, $json, FILE_APPEND);
I also can't establish the square bracket after value. How can I fix this?
As I said in my comment
$json = file_get_contents( $file );
// $json is now a string
$data = json_decode($json);
// $data is a PHP object
// So lets call the second array $data->someArray
// since I do not know what it is called looking at your file
// convert form data to PHP array format
$postArray = array(
"name" => $_POST['name'],
"desc" => $_POST['desc'],
"values" => array(
"id" => $_POST["value_id"],
"from" => $_POST['value_from'],
"to" => $_POST['value_to'],
"desc" => $_POST['value_desc'],
"customClass" => $_POST['value_class'],
"label" => $_POST['value_label']
)
); //you might need to process any other post fields you have..
// $postArray is a PHP object
// $json = json_encode( $postArray ); // do NOT convert here
array_push($data->someArray, $postArray);
$json = json_encode($data);
// write to file
file_put_contents( $file, $json, FILE_APPEND);
Your values field is an array of objects instead of an object (the encoding of a php associative array is a json oject). So for values to have square brackets instead of "values" => array() you would need "values" => array( array("id" => ... etc. ) )
As for your first problem you've inverted the json_encoding. First push your postArray into data, then json_encode data.