Remove Value from JSON PHP

7.4k views Asked by At

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>&nbsp;<\/p>\n",
  "excerpt":"<p>content &nbsp;<\/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.");
}

}

3

There are 3 answers

0
OndraTom On

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);
0
derdida On

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);
1
Double H On
 $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);