Laravel add seperate key-value pair to collection JSON - php

I have a Laravel controller that returns a collection of items (in this case Answers):
return AnswerResource::collection($correctAns);
This returns a JSON object as expected of course. How would I go about appending an item to that object so it's more like this?
{
"data": [
{
"id": "2",
"answer_text": "True"
},
{
"id": "3",
"answer_text": "False"
}
],
"testKey": "arsnteio12345"
}
(where the testKey thing is what's added)

Try something like this
return Response::json(['data '=> $correctAns, 'testKey' => 'arsnteio12345'],200);

Related

How to return valid JSON array by WordPress REST API .. Not JSON object?

I'm working on WordPress site and been asked to supply mobile developer by JSON API data for a slider. I have to add the slider data like images and titles etc. I've found a plugin which serve an end point called MetaSlider. I've did required things and the response was perfect. but the developer replied by this:
"I am not talking about data. It should be a valid JSON array. Plz have a look at data structure of response object
"0": {
"id": 2669,
"title": "New Slideshow",
This is not valid json. It should be a JSON Array like this
[ {
"id": 2669,
"title": "New Slideshow","
Does any one have a clue?
I looked for a plugin that can do the job but I didn't find any.
I was experiencing the same issue.
If your array is as result of using array_map, wrap your response with array_values($data).
This is the function I have as a callback for register_rest_route;
public function terms_ep( $request ) {
$terms = get_terms('my_taxonomy', []);
$data = array_map(function($t){
return [
'id' => $t->term_id,
'name' => $t->name
];
}, $terms);
return rest_ensure_response( array_values($data) );
}
With array_values it produces a nice json array:
[
{
"id": 13,
"name": "A"
},
{
"id": 12,
"name": "B"
}
]
Without the response is this object response:
{
"0": {
"id": 13,
"name": "A"
},
"2": {
"id": 12,
"name": "B"
}
}

modify json data in php laravel

I've a sample json data
{
"cities": {
"total": 100,
"count":5000,
"cities_list" : [{
"name": "city1",
"count": 1000
},
{
"name": "city2",
"count": 2000
}
]
}
}
How can I append the cities_list array directly to cities which would look like
{
"cities": [{
"name": "city1",
"count": 1000
},
{
"name": "city2",
"count": 2000
}
]
}
Not sure, about all the stuff, but i assume your "json" or just associative array is in variable (for example foo)
Now you should set:
$foo["cities"] = $foo["citites"]["citites_list"];
Let's say that your JSON result is stored in a variable called $results
$results = json_decode($results,true); //convert json to array
$modifiedArray= [];
$modifiedArray= $results['cities']['cities_list']->map(function ($item, $key) {
return ['cities'][][
'name' => $item->name,
'count' => $item->count
];
});
This is more of a laravel approach since you also tagged laravel. Your modified array is an array type if you want to be a JSON again you have to encode it into a JSON.
You can use the Unset function
$data= json_decode($your_json);
$json_arr = json_decode($your_json, true);
unset($data->total);
unset($json_arr['total']);

Convert Single Object into an Array containing that Object

I have a number of JSON files and when there is a single object in them, their datatype is inconsistent. I am trying to alter the files that contain one item so that the element I am referencing is always an array.
Here's an example of a 'good' JSON file:
{
"apiv2": {
"items": [{
"id": "00001",
"name": "ITEM 1"
}, {
"id": "00002",
"name": "ITEM 2"
}]
}
}
In PHP terms, $json->apiv2->items is always an array I can apply the same functions to.
Every so often I have a JSON file that contains one item:
{
"apiv2": {
"items": {
"id": "00003",
"name": "ITEM 3"
}
}
}
When I attempt to iterate through 'items' with the same functions, they fail as it is now an object instead of an array.
My goal is to alter the JSON data and rewrite the file so the single item files are consistent with the multiple item files:
{
"apiv2": {
"items": [{
"id": "00003",
"name": "ITEM 3"
}]
}
}
Maybe it's because it's Friday afternoon, but I can't seem to wrap my head around this one. I thought it would be as simple as:
$json->apiv2->items = (array) $json->apiv2->items;
But that just turns it into an array with two elements, "id" and "name", not one element with the object.
As I said in the comments
When you do
$json->apiv2->items = (array) $json->apiv2->items;
PHP will convert $items to an actual array [ "id" => "00003", "name" => "ITEM 3"]
Which will give you the results ['items' => [ "id" => "00003", "name" => "ITEM 3"]]
Instead of converting your object, you need to wrap it
$json->apiv2->items = [$json->apiv2->items];
More advanced: since sometimes items can be an array and sometimes not, you can make a function [1] to wrap them
function wrap($value)
{
if (is_null($value)) {
return [];
}
return is_array($value) ? $value : [$value];
}
$json->apiv2->items = wrap($json->apiv2->items);
POC : https://3v4l.org/7p9b0
[1] Stolen from Laravel helpers
Use json_decode() and access it like this:
$json = '{"apiv2":{"items": [{"id": "00001", "name": "ITEM 1" }, {"id": "00002", "name": "ITEM 2" }]}}';
print_r(json_decode($json, true)['apiv2']['items']);

Return an Array instead of Object

I am fetching data from DB like this
$endResult = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
if (!isset($endResult[$row['car']])) {
$endResult[$row['car']]= (object) array(
'car' => $row['car'],
'carModel' => $row['carModel'],
'colors' => array()
);
}
$endResult[$row['car']] -> colors [] = (object) array(
'paintedOn' => $row['paintenOnDate'],
'paintedBy' => $row['paintedBy']
);
}
//return with slim.php
$response->body(json_encode($endResult));
and result I am getting
{"1":
{
"car": "1",
"carModel": "model-1",
"colors": [
{
"paintedOn": "2014-11-07",
"paintedBy": "5"
},{
"paintedOn": "2014-11-08",
"paintedBy": "6"
}]
},
"2":{
"car": "2",
"carModel": "model-2",
"colors": [
{
"paintedOn": "2014-11-09",
"paintedBy": "7"
},{
"paintedOn": "2014-11-10",
"paintedBy": "8"
}]
}
}//<--replace this with []
Even if $endResult is declared as Array I am getting {} brackets, how could I replace "Object" brackets with "Array" brackets?
UPDATE: I can't remove json_encode as the front-end (backbone) expecting collection
UPDATE 2: $endResult = array(); return [...]
but this $endResult[$row['car']]= (object) array(...) convert it to {...}
You can't achieve what you want because it would result in invalid JSON. According to json.org:
An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
So you can only have values in an array. Because you are adding a name to the value, it must become an object.
If you really want your JSON to be wrapped in an array you need to remove the first-level names, in your example "1" and "2":
[
{
"car": "1",
"carModel": "model-1",
"colors": [
{
"paintedOn": "2014-11-07",
"paintedBy": "5"
},
{
"paintedOn": "2014-11-08",
"paintedBy": "6"
}
]
},
{
"car": "2",
"carModel": "model-2",
"colors": [
{
"paintedOn": "2014-11-09",
"paintedBy": "7"
},
{
"paintedOn": "2014-11-10",
"paintedBy": "8"
}
]
}
]
Remove the conversion to JSON. Also "declaration" in PHP doesn't matter. You can still assign different types in the course of your program.
I think the PHP function json_decode Should help you here. This turns the JSON format into an array.
use json_decode($data,true) for convert returned data in to array.
simply use array_values function:
$array = array_values($response);

FuelPHP + JSON + Ajax

For example, when I use Model_Trabalhos::query()->related('categoria'), I Get a normal JSON like this:
{
"id": "1",
"categoria_id": "2",
"empresa": "Veja",
"nome": "Veja",
"thumb_pequena": "jobs/digital/veja/thumb.jpg",
"thumb_grande": "jobs/digital/veja/thumb_grande.jpg",
"destaque": "0",
"categoria": {
"id": "2",
"titulo": "Digital"
},
"imagens": {
"1": {
"id": "1",
"url": "jobs/digital/veja/1.png",
"legenda": "",
"job_id": "1"
},
"2": {
"id": "2",
"url": "jobs/digital/veja/2.png",
"legenda": "",
"job_id": "1"
}
}
}
instead, I wanted to receive back this:
[
{
"id": "3",
"categoria_id": "2",
"empresa": "Valor Econômico",
"nome": "Novo Site",
"thumb_pequena": "jobs/digital/valor-economico/thumb.jpg",
"thumb_grande": "jobs/digital/valor-economico/thumb_grande.jpg",
"destaque": "1",
"categoria": {
"id": "2",
"titulo": "Digital"
},
"imagens": [
{
"id": "3",
"url": "jobs/digital/valor-economico/1.png",
"legenda": "",
"job_id": "3"
}
]
}
]
You see? In the second case, it's wrapped in an array, and I wanted to know if there's a function in FuelPHP native that wrap the content to be ordered.
I'm in trouble... I'm using FuelPHP + ORM to get all my records from a database and generating a JSON to use with JavaScript and Ajax, but in Chrome, the JSON is not following the order by defined, is there any workaround for this problem?
If you're wanting your information in a certain way you could follow that query with a foreach loop that would add them to an array of arrays (translated to an array of JSON objects) once converted to JSON.
$query = Model_Trabalhos::query()->related('categoria')
$categories = array();
foreach ($query as $category) {
$categories[] = array(
'id' => $category->id,
...
);
}
return $categories;
It's an old question, but i had the same problem now and colud resolve like the answer that i posted in https://stackoverflow.com/a/34242106/5670195.
In case it is a function that converts into simple array, the objects returned as the relationship of ORM.

Categories