I am new to PHP and I am working on wordpress JSON api. I want to remove Key:value pair inside a JSON array. Please help
{
"status":"ok",
"post":{
"id":23,
"type":"post",
"slug":"head-ache",
"url":"http:\/\/xyz.com\/maruthuvam\/2015\/06\/17\/head-ache\/",
"status":"publish",
"title":"Head Ache",
"title_plain":"Head Ache",
"content":"<p>content<\/p>\n<p> <\/p>\n",
"excerpt":"<p>content <\/p>\n",
"date":"2015-06-17 19:35:47",
"modified":"2015-06-18 07:35:39",
"categories":[
{
"id":1,
"slug":"head",
"title":"Head",
"description":"http:\/\/xyz.com\/maruthuvam\/wp-content\/uploads\/2015\/06\/universa_-male_head_3d_model_01.jpg",
"parent":0,
"post_count":3
}
],
"tags":[
],
"author":{
"id":1,
"slug":"admin",
"name":"admin",
"first_name":"",
"last_name":"",
"nickname":"admin",
"url":"",
"description":""
},
"comments":[
],
"attachments":[
],
"comment_count":0,
"comment_status":"closed",
"custom_fields":{
}
},
"next_url":"http:\/\/xyz.com\/maruthuvam\/2015\/06\/17\/head- lice\/"
}
For example I want to remove "slug":"head-ache" from "post" and "post_count":0, from "categories" and "next-url". Please help.
UPDATE::
I have added the code in core.php and its not working. Can you please help me out.
public function get_post() {
global $json_api, $post;
$post = $json_api->introspector->get_current_post();
if ($post) {
$previous = get_adjacent_post(false, '', true);
$next = get_adjacent_post(false, '', false);
$response = array(
'post' => new JSON_API_Post($post)
);
if ($previous) {
$response['previous_url'] = get_permalink($previous->ID);
}
if ($next) {
$response['next_url'] = get_permalink($next->ID);
}
// parsing json
$arr = decode_json($response);
// removing the value
unset($arr['post']['slug']);
// and back to json
$response = json_encode($arr);
return $response;
} else {
$json_api->error("Not found.");
}
}
Just convert it to a PHP Array:
$jsonArray = json_decode($jsonString);
Remove the Keys
unset($jsonArray['post']['slug']);
And convert back:
$newJson = json_encode($jsonArray);
You need to parse it to ordinary array, then remove what you want and encode it back to json:
// parsing json
$arr = decode_json($yourJson);
// removing the value
unset($arr['post']['slug']);
// and back to json
$editedJson = json_encode($arr);
$a= json_decode($data,true);
unset($a['post']['slug']);
unset($a['next_url']);
$count= count($a['post']['categories']);
for($i=0 ; $i < $count ; $i++){
unset($a['post']['categories'][$i]['post_count']);
}
echo json_encode($a);
Related
I am trying to sent response in that form
{"files":[{"webViewLink":""},{"webViewLink":""}]}
But I'm getting response like that
{"files":[{"webViewLink":"""}]}{"files":[{"webViewLink":"""}]}
Here is my PHP code:
<?php
$idtemp = extractfiles($fol_id, $email);
foreach ($idtemp['items'] as $val) {
$id = $val['id'];
$val = array(
"webViewLink" => 'https://drive.google.com/file/d/'.$val['id'].'/view?usp=drivesdk"'
);
$enc = json_encode($val);
$val = '{"files":['.$enc.']}';
echo($val);
Please help me to fix code i need response in that way
{"files":[{"webViewLink":""},{"webViewLink":""}]}
You should no do $val = '{"files":['.$enc.']}';
Use json_encode to make json, don't do it manual
Create an object with desired keys outside the loop
Push anything to the desired array
Convert to json
<?php
$idtemp = extractfiles($fol_id, $email);
$json = (object) [
"files" => []
];
foreach ($idtemp['items'] as $val) {
$json->files[] = (object) [
"webViewLink" => 'https://drive.google.com/file/d/'.$val['id'].'/view?usp=drivesdk"'
];
}
$json = json_encode($json);
echo($json);
If I use some dummy values to create an example, the output is:
{
"files": [
{
"webViewLink": "https://drive.google.com/file/d/1/view?usp=drivesdk\""
},
{
"webViewLink": "https://drive.google.com/file/d/2/view?usp=drivesdk\""
},
{
"webViewLink": "https://drive.google.com/file/d/3/view?usp=drivesdk\""
}
]
}
As you can test in this online demo
So from a Get request I get back a response in this structure:
{
"chromeosdevices" : [
{
"somekey" : "somevalue",
"annotatedUser" : "annotatedUserValue",
"activeTimeRanges" : [
{
"date" : "dateValue",
"activeTime" : "activeTimeValue"
}
],
"somekey" : "somevalue",
},
]
}
How can I access both DateValue and ActiveTimeValue?
I have tried it with this code:
$dec = json_decode($response);
$filteredResults= array();
if (! empty($dec->chromeosdevices)) {
foreach ($dec->chromeosdevices as $chromeosdevice) {
$user['annotatedUser'] = $chromeosdevice->annotatedUser;
$user['activeTimeRanges_date'] = $chromeosdevice->activeTimeRanges->date;
$user['activeTimeRanges_activeTime'] = $chromeosdevice->activeTimeRanges -> activeTime;
$filteredResults[] = $user;
}
}
echo '<pre>';print_r($filteredResults);echo '</pre>';
However, I only get back the annotatedUser, but not the date and active time. Why is that?
As it is another object in an array use $chromeosdevice->activeTimeRanges[0]->date;
That is in an array so maybe another loop would be the safest way to deal with this
$dec = json_decode($response);
$filteredResults= array();
if (! empty($dec->chromeosdevices)) {
foreach ($dec->chromeosdevices as $chromeosdevice) {
$user = []; // init and remove last loops info
$user['annotatedUser'] = $chromeosdevice->annotatedUser;
foreach ($chromeosdevice->activeTimeRanges as $tr) {
$user['activeTimeRanges_date'][] = $tr->date;
$user['activeTimeRanges_activeTime'][] = $tr->activeTime;
}
$filteredResults[] = $user;
}
}
echo '<pre>';print_r($filteredResults);echo '</pre>';
My API return single item as object:
"data":{"id":1,"name":"Test"}
but i need this item in array, like this:
"data":[{"id":1,"name":"Test"}]
data.json:
[
{"id": 1, "name":"Test"},
{"id": 2, "name": "Test2"}
]
api.php:
function getData2($id) {
$jsonString = '';
$jsonData = file_get_contents($jsonString);
$data2 = json_decode($jsonData, true);
return $data2[$id - 1];
}
if (!empty($_GET['id'])) {
$a = getData2($_GET['id']);
}
response($a);
function response($data) {
header("HTTP/1.1 ".$status);
$response['data'] = $data;
$jsonResponse = json_encode($response);
echo $jsonResponse;
}
Thanks in advance.
Just put data in an array like this:
function response($data) {
header("HTTP/1.1 ".'200');
$response['data'] = [$data];
$jsonResponse = json_encode($response);
echo $jsonResponse;
}
notice $data in this line $response['data'] = [$data];
Im trying to decode json and get value from the json code.
[{
"restaurant_id":1,
"menu_template_id":2,
"add_food_item_a":1,
"menu_category_id":1,
"status":0
} ,
{
"restaurant_id":1,
"menu_template_id":2,
"add_food_item_a":2,
"menu_category_id":1,
"status":0
}]
i need to read from this json and create an array with add_food_item_a and status.
currently I'm using like this
public function readJson()
{
$json_obj = json_decode('');
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]) && !empty($GLOBALS["HTTP_RAW_POST_DATA"])) {
$json_text = $this->cleanMe($GLOBALS["HTTP_RAW_POST_DATA"]);
// now insert into user table
$json_obj = json_decode($json_text);
}
return $json_obj;
}
and I call this function like
$add_food_item_a = isset($json_obj->add_food_item_a) ? $json_obj->add_food_item_a : '';
but can't read from this array of json code
Are you trying to fetch the value of 'add_food_item_a' and 'status'
<?php
$json='[{
"restaurant_id":1,
"menu_template_id":2,
"add_food_item_a":1,
"menu_category_id":1,
"status":0
} ,
{
"restaurant_id":1,
"menu_template_id":2,
"add_food_item_a":2,
"menu_category_id":1,
"status":0
}]';
echo "<pre>";
$array = json_decode($json,1);
print_r($array);
foreach($array as $value)
{
echo "\n".$value['add_food_item_a'];
echo "\n".$value['status'];
}
In PHP, how to get a JSON value from a variable path ?
Here is a sample json and a function with 2 params: a json variable, and path split into keys.
$myjson = json_decode('{
"myKey1": {
"myKey2": {
"myKey3": {
"myKey4": "myfinalvalue"
}
}
}
}');
function getJSONValue($myjson, $pathkey) {
// split path keys by ";"
$myjson-> ?? $pathkey ??
}
echo getJSONValue($myjson, "myKey1;myKey2;myKey3;myKey4");
// Should display "myfinalvalue"
the static equivalent would be to do:
$myjson->myKey1->myKey2->myKey3->myKey4;
I tried:
$myjson->$pathkey
but unfortunately, it doesn't work...
Actually, your question has nothing to do with JSON. This is how you can get a value from a nested object:
function getValue($obj, $path) {
foreach(explode(';', $path) as $key) {
$obj = $obj->$key;
}
return $obj;
}
As for the JSON part, your example is not a valid JSON. It should be like this:
$myjson = json_decode('{
"myKey1": {
"myKey2": {
"myKey3": {
"myKey4": "myfinalvalue"
}
}
}
}');
Also, php objects are case-sensitive, if you have myKey in the object, it should be myKey (and not mykey) in the path string.
function getJSONValue($myjson, array $pathkey) {
foreach($pathkey as $val){
$myjson = $myjson->{$val};
}
return $myjson;
}
$myjson = json_decode('{"myKey1": {"myKey2": {"myKey3": {"myKey4": "myfinalvalue"}}}}');
echo getJSONValue($myjson, ["myKey1","myKey2","myKey3","myKey4"]);
live example: http://codepad.viper-7.com/1G78Fi
Something like this:
function getJSONValue() {
$args = func_get_args();
$json = array_shift($args);
$key = array_shift($args);
$value = $json->$key;
if(is_object($value)) {
array_unshift($args, $value);
return call_user_func_array('getJSONValue', $args);
}
return $value;
}
No error checking.
Seems like you are mixing PHP and JS. check this out to see how to create a Json string, then getting an onject out of it, and accessing keys:
$myjson = json_encode(array(
'myKey1' => array(
'mykey2' => array(
'mykey3' => array(
'myKey4' => "myfinalvalue"
)
)
)
));
$obj = json_decode($string);
echo $obj->myKey1->mykey2->mykey3->myKey4
// "myfinalvalue"
or pasting the json directly:
$obj = json_decode(
'{
myKey1: {
mykey2: {
mykey3: {
myKey4: "myfinalvalue"
}
}
}
}');
echo $obj->myKey1->mykey2->mykey3->myKey4
// "myfinalvalue"
To understand it betterm, read about JSON_DECODE