Rest API single item - json format problem - php

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

Related

How to properly format a JSON array | PHP

Essentially I have the following array with various values that are being passed through a function. The output of each needs to then be assembled into a JSON Array that looks like the following:
"response": {
"firstvalue": 4,
"secondvalue": 1,
"thirdvalue": "String Response 1",
"fourthvalue": "String Response 2"
}
Code So Far:
<?php
header('Content-Type: application/json');
$arrayvalues =
["34jkw9k2k9w",
"k4otk320el01oeoo20",
"30f0w2l020wk3pld==",
"3c2x3123m4k43=="];
foreach($arrayvalues as $item) {
$decrypted = myFunction($item, $action = 'decrypt');
$response["firstvalue"] = $decrypted;
$response["secondvalue"] = $decrypted;
$response["thirdvalue"] = $decrypted;
echo json_encode($response);
}
?>
How can this be done?
header('Content-Type: application/json');
$arrayvalues =
["34jkw9k2k9w",
"k4otk320el01oeoo20",
"30f0w2l020wk3pld==",
"3c2x3123m4k43=="];
// Is this necessary?
$keys = ['firstvalue', 'secondvalue', 'thirdvalue', 'fourthvalue'];
$result = [];
foreach($arrayvalues as $idx => $item) {
$result[$keys[$idx]] = myFunction($item, $action = 'decrypt');
}
echo json_encode(['response' => $result], JSON_PRETTY_PRINT);
UPD: Added response nesting.

json array is repeating index

this is my code :
if ($API->connect("192.168.81.130", "admin", "")) {
$API->write('/ip/route/print', false);
$API->write('=.proplist=.id', false);
$API->write('=.proplist=dst-address', false);
$API->write('=.proplist=pref-src', false);
$API->write('=.proplist=gateway');
$result = $API->read();
$API->disconnect();
foreach ($result as $route){
$response['id'] = $route['.id'];
$response['dst-address'] = $route['dst-address'];
if (isset($route['pref-src'])) {
$response['pref-src'] = $route['pref-src'];
} else {
$response['pref-src'] = "";
}
$response['gateway'] = $route['gateway'];
$array[] = $response;
echo json_encode($array);
}
}
and the output is :
[{"id":"*2","dst-address":"0.0.0.0\/0","pref-src":"","gateway":"192.168.1.1"}][{"id":"*2","dst-address":"0.0.0.0\/0","pref-src":"","gateway":"192.168.1.1"},{"id":"*420639B3","dst-address":"192.168.81.0\/24","pref-src":"192.168.81.130","gateway":"ether1"}]
result for "[{"id":"*2","dst-address":"0.0.0.0/0","pref-src":"","gateway":"192.168.1.1"}]" is show twice.
i want the out put like this :
> [{"id":"*2","dst-address":"0.0.0.0\/0","pref-src":"","gateway":"192.168.1.1"},{"id":"*420639B3","dst-address":"192.168.81.0\/24","pref-src":"192.168.81.130","gateway":"ether1"}].
can anyone help me?.
You need to initialize your array each time round the loop otherwise you are just adding to it each time, hence the duplication
You also need to move the echo of the json string to outside the loop
foreach ($result as $route){
$response = array();
$response['id'] = $route['.id'];
$response['dst-address'] = $route['dst-address'];
if (isset($route['pref-src'])) {
$response['pref-src'] = $route['pref-src'];
} else {
$response['pref-src'] = "";
}
$response['gateway'] = $route['gateway'];
$array[] = $response;
}
echo json_encode($array);

Remove Value from JSON PHP

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

Access JSON through variable path in PHP

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

Count how many of the same element in json

Im parsing json with php in this simple piece of code
<?php
$json = file_get_contents('list.json');
$data = json_decode($json,true);
$records=$data['records'];
foreach($records as $record)
{
echo $record['number']." ".$record['opened_at'];
}
?>
But i want to echo how many 'number' element are in my json file exemple bellow
{
"records":[
{
"number":"INC018****",
},
{
"number":"INC018****",
},
{
"number":"INC018****",
},
{
"number":"INC018****",
},
<?php
$json = file_get_contents('list.json');
$data = json_decode($json,true);
$records=$data['records'];
$numberCount = 0;
foreach($records as $record)
{
$numberCount += isset($record['number']); // Here we go
echo $record['number']." ".$record['opened_at'];
}
echo $numberCount;
?>
This function might be helpful: http://www.php.net/manual/en/function.array-count-values.php
$counts = array_count_values($records);
$numberCount = $counts['number'];

Categories