How can I encode an array into json with additional data? - php

I am creating a json file from my array:
$file = json_encode($array);
The json file will look like this:
[
{
"name": "file1.html",
"date": "2019-01-29T20:33:57.000163Z",
"size": "348"
}
{
"name": "file2.xml",
"date": "2019-01-29T20:33:57.000167Z",
"size": "401"
}
{
"name": "file3.html",
"date": "2019-01-29T20:33:57.000171Z",
"size": "1314"
}
]
But I need to create a json file with some little bit different format. The output I need is:
{
"draw": 1,
"recordsTotal": 5000,
"recordsFiltered": 5000,
"data": [
{
"name": "file1.html",
"date": "2019-01-29T20:33:57.000163Z",
"size": "348"
}
{
"name": "file2.xml",
"date": "2019-01-29T20:33:57.000167Z",
"size": "401"
}
{
"name": "file3.html",
"date": "2019-01-29T20:33:57.000171Z",
"size": "1314"
}
]
}
Is this possible with json_encode?

Create a new array with rest of the info and assign current array data into it as well.
$newArray = array(
'draw'=> 1,
'recordsTotal'=> 5000,
'recordsFiltered'=> 5000,
'data'=>$array
);
$file = json_encode($newArray);

Related

Extract element from nested JSON

There is json response:
{
"id": "1234567890123456789",
"creation_date": 12345678,
"event": "WAITING_PAYMENT",
"version": "2.0.0",
"data": {
"product": {
"id": 213344,
"name": "Product Name",
"has_co_production": false
},
"affiliates": [
{
"name": "Affiliate name"
}
],
"buyer": {
"email": "buyer#email.com"
},
"producer": {
"name": "Producer Name"
},
"commissions": [
{
"value": 0.65,
"source": "MARKETPLACE"
},
{
"value": 3.10,
"source": "PRODUCER"
}
],
"purchase": {
"approved_date": 1231241434453,
"full_price": {
"value": 134.0
},
"original_offer_price": {
"currency_value": "EUR"
"value": 100.78,
},
"price": {
"value": 150.6
},
"order_date": "123243546",
"status": "STARTED",
"transaction": "HP02316330308193",
"payment": {
"billet_barcode": "03399.33335 33823.303087 198801027 2 876300015000",
"billet_url": "https://billet-link.com/bHP023163303193",
}
},
"subscription": {
"status": "ACTIVE",
"plan": {
"name": "plan name"
},
"subscriber": {
"code": "12133421"
}
}
}
}
My question is how to extract data["buyer"]["email"] in PHP ?
I only need to extract the email information from the buyer table inside the data table.
First, you need to decode the json to a PHP array (or an object), then you can access the requested information from the decoded data.
$data = json_decode('the json string most place here', true);
$email = $data['buyer']['email'];
Place your json string in the first argument of json_decode() function.

How to group JsonArray result content in json index

In my JsonArray result, I want to put all the content in index [{'data':{contenthere}}]
Here is my code :
$data = [];
$gr = []; //some data here
foreach($gr as $g) {
$data[] = [
'id' => $g['id'],
'name' => $g['name'],
'phone' => $g['pĥone']
]
}
return $data;
return $data output :
string(249) "[
{
"id": "112",
"name": "john",
"phone": "XXXXXXXXX"
},
{
"id": "213",
"name": "mike",
"phone": "XXXXXXXXX"
},
{
"id": "246",
"name": "jess",
"phone": "XXXXXXXXX"
},
]
cool, now I want to put all this in ['data'] so the result needed :
string(249) "[
{
"data": {
{
"id": "112",
"name": "john",
"phone": "XXXXXXXXX"
},
{
"id": "213",
"name": "mike",
"phone": "XXXXXXXXX"
},
{
"id": "246",
"name": "jess",
"phone": "XXXXXXXXX"
},
}
}
]
As Google JSON Style
I tried the $data[]['data'] but the "data": repeats in each object
foreach($gr as $g) {
$data[]['data'] = ...
I thought do do group_by function but I think that there is a simple solution for that
I'm not sure if you really need the extra array at the top level, but use...
return [["data" => $data]];
should give you the result.
Use json_encode to achieve this:
$json = json_encode(array('data' => $data));
print_r($json);
Result:
{
"data": [
{
"id": "112",
"name": "john",
"phone": "XXXXXXXXX"
},
{
"id": "213",
"name": "mike",
"phone": "XXXXXXXXX"
},
{
"id": "246",
"name": "jess",
"phone": "XXXXXXXXX"
}
]
}

Set name in json format in php/laravel

How to set name to JSON object in laravel as I want to display for a plugin in Vue js for image gallery. Whenever I pass data I Got this error : Expected Object, got Array.
{
"normal_size": [
{
"id": 1,
"image": "MICMIMC30651-6.jpg",
"url": "http://localhost:8000/images/product/preview/MICMIMC30651-6.jpg"
},
{
"id": 2,
"image": "MICMIMC30651-61.jpg",
"url": "http://localhost:8000/images/product/preview/MICMIMC30651-61.jpg"
},
{
"id": 3,
"image": "MICMIMC30651-62.jpg",
"url": "http://localhost:8000/images/product/preview/MICMIMC30651-62.jpg"
},
{
"id": 4,
"image": "MICMIMC30651-63.jpg",
"url": "http://localhost:8000/images/product/preview/MICMIMC30651-63.jpg"
}
]
}
output I wanted :
image : {
"normal_size": [
{
"id": 1,
"image": "MICMIMC30651-6.jpg",
"url": "http://localhost:8000/images/product/preview/MICMIMC30651-6.jpg"
},
{
"id": 2,
"image": "MICMIMC30651-61.jpg",
"url": "http://localhost:8000/images/product/preview/MICMIMC30651-61.jpg"
},
{
"id": 3,
"image": "MICMIMC30651-62.jpg",
"url": "http://localhost:8000/images/product/preview/MICMIMC30651-62.jpg"
},
{
"id": 4,
"image": "MICMIMC30651-63.jpg",
"url": "http://localhost:8000/images/product/preview/MICMIMC30651-63.jpg"
}
]
}
`
Laravel product controller code to pass data to vue component
$normal_size = DB::table('products_images')->where([['products_id', '=', $product]])
->select('products_images.id','products_images.image')
->get()->ToArray();
foreach($normal_size as $value)
{
$value->url = 'http://localhost:8000/images/product/preview/'.$value->image;
}
$output = (array('normal_size' => $normal_size));
return response()->json(($output));
Decode your JSON to convert an array. Format the array structure you want and encode the array to JSON.
$data = '{
"normal_size": [
{
"id": 1,
"image": "MICMIMC30651-6.jpg",
"url": "http://localhost:8000/images/product/preview/MICMIMC30651-6.jpg"
},
{
"id": 2,
"image": "MICMIMC30651-61.jpg",
"url": "http://localhost:8000/images/product/preview/MICMIMC30651-61.jpg"
},
{
"id": 3,
"image": "MICMIMC30651-62.jpg",
"url": "http://localhost:8000/images/product/preview/MICMIMC30651-62.jpg"
},
{
"id": 4,
"image": "MICMIMC30651-63.jpg",
"url": "http://localhost:8000/images/product/preview/MICMIMC30651-63.jpg"
}
]
}';
$output = json_encode(['image' => json_decode($data, true)]);
echo $output;
Working demo.
SOLUTION:
Just adjust the output format before sending.
$output= ['image' => json_decode($data)];
or
$output= array("image" => json_decode($data));

parse extended json output file from cucumber with php

i am tring to parse a special json content. I got this as an output file from a cucumber execution. The goal is it to decode some values like the name the status and some other content. How can i encode that.
Another concern would be a transformation of json into a CSV.
It is not important for me to use php. Java or Perl would be an alternative.
This file I am gonna call in php with:
$jsonconntent = file_get_contents("/home/xxx/test1.json");
The json conten looks like this (I posted only the beginning):
[
{
"uri": "features/complete_ski.feature",
"id": "complete_ski_with_time",
"keyword": "Feature",
"name": "Complete_Ski_with_time",
"description": "",
"line": 1,
"elements": [
{
"id": "complete_ski_with_time;time_part_preamble",
"keyword": "Scenario",
"name": "time_part_preamble",
"description": "",
"line": 3,
"type": "scenario",
"before": [
{
"output": [
"Default Timestamp start: 1516024716000"
],
"match": {
"location": "features/support/env.rb:32"
},
"result": {
"status": "passed",
"duration": 191690
}
},
{
"match": {
"location": "capybara-2.17.0/lib/capybara/cucumber.rb:13"
},
"result": {
"status": "passed",
"duration": 52117
}
},
{
"match": {
"location": "capybara-2.17.0/lib/capybara/cucumber.rb:21"
},
"result": {
"status": "passed",
"duration": 25885
}
}
],
"steps": [
{
"keyword": "Given ",
"name": "a Android A-Party",
"line": 4,
"output": [
"Got handset with number unvisable, IMSI: notfor, android-Id: yourfone, VNC: 11111, port: 9981"
],
"match": {
"location": "features/step_definitions/idrp_steps.rb:11"
},
"result": {
"status": "passed",
"duration": 1415024760
},
"after": [
{
"match": {
"location": "features/support/env.rb:24"
},
"result": {
"status": "passed",
"duration": 264339
}
}
]
}
Use:
$data = json_decode($jsonconntent, true);
You will have the data with javascript objects as arrays, not PHP objects.
To save it as CSV, it depends on the structure of the data. In this case, it is complicated:
{
"uri": "features/complete_ski.feature",
"id": "complete_ski_with_time",
"keyword": "Feature",
"name": "Complete_Ski_with_time",
"description": "",
"line": 1,
"elements": [
{
"id": "complete_ski_with_time;time_part_preamble",
"keyword": "Scenario",
"name": "time_part_preamble",
"description": "",
"line": 3,
...
How do you put the data in the column elements? Data is so nested that it cannot be transformed into a tabular format with column headers and one value per column in each row.
As to how to access the data, you can do this:
$first_element_id = $data[0]['elements'][0]['id'];
foreach ( $data as $item ) {
$uri = $item['uri'];
foreach ( $item['elements'] as $element ) {
$name = $element['name'];
}
}
As asked in one of the comments, this is how to access the 'Default Timestamp start':
foreach ($data as $item) {
foreach ($item['elements'] as $element) {
foreach ($element['before'] as $before) {
if (isset($before['output'])) {
foreach ($before['output'] as $output) {
echo sprintf("%s\n", $output);
}
}
}
}
}

Separate JSON response

I am getting a response using Unirest library, i need to separate the data, so that based on that data i can call my next query. Here is full json response i am getting while using Unirest library
echo '<pre>'; print_r($response->raw_body); echo '</pre>';
{
"status": "success",
"images": [
"http://www.example.com/12.jpg"
],
"photos": [
{
"url": "http://www.example.com/12.jpg",
"width": 205,
"tags": [
{
"confidence": 0.978945010372561,
"center": {
"y": 64,
"x": 129
},
"height": 79,
"width": 79,
"tid": "31337",
"attributes": [
{
"smile_rating": 0.56,
"smiling": true,
"confidence": 0.56
}
],
"uids": [
{
"confidence": 0.35399999999999998,
"prediction": "SE2",
"uid": "SE2#SEA1"
},
{
"confidence": 0.28999999999999998,
"prediction": "SE1",
"uid": "SE1#SEA1"
},
{
"confidence": 0.16,
"prediction": "Star1",
"uid": "Star1#SEA1"
},
{
"confidence": 0.106,
"prediction": "SE3",
"uid": "SE3#SEA1"
},
{
"confidence": 0.037999999999999999,
"prediction": "SE6",
"uid": "SE6#SEA1"
},
{
"confidence": 0.035000000000000003,
"prediction": "SE5",
"uid": "SE5#SEA1"
},
{
"confidence": 0.017999999999999999,
"prediction": "SE4",
"uid": "SE4#SEA1"
}
]
}
],
"height": 206
}
]
}
What i am trying is to print like this
Confidence : 0.35399999999999998
Similar: Test2
Well, provided it is a valid JSON string, just use a simple json_decode() with true flag so that it returns an array. Example:
$data = json_decode($response->raw_body, true);
$i = 0;
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
if($i == 5) break;
echo 'Confidence: ' . $value['confidence'] . '<br/>';
echo 'Similar: ' . $value['prediction'] . '<br/><br/>';
$i++;
}
The release of Unirest 2.0 had many improvements including ability to set custom JSON decode flags
this gives you more control over the response body type parsing method (json_decode)
Disclaimer: I'm the author of unirest-php and I work at Mashape.

Categories