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.
Related
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.
I have a wordpress endpoint and I have some json data.
Unfortunately I dont know how to return this json data in the function. I tried json_decode but it doesn't return anything. Then endpoint works. If I use json_encode it returns data, but also include linebreaks and stuff. The problem seems to be with the syntax as it is already a complete json what I have. How can I return something that is already in json syntax?
add_action('wp_ajax_nopriv_inboundCall', 'testFunction');
add_action('wp_ajax_inboundCall', 'testFunction');
function testFunction() {
echo json_decode('{
"testData": [
{
"_id": "1",
"name": "testName1"
},
{
"_id": "2",
"name": "testName2"
},
],
"testState": {
"1": [
1,
0
"2": [
1,
0
]
}
}');
die();
}
function testFunction() {
return json_decode('{
"testData": [
{
"_id": "1",
"name": "testName1"
},
{
"_id": "2",
"name": "testName2"
},
],
"testState": {
"1": [
1,
0
"2": [
1,
0
]
}
}'); }
I saved the output of json_decode to a variable and then run json_encode on that variable. Now it seems to work.
function inboundCall() {
$json = json_decode('{
"topics": [
{
"_id": "1",
"name": "davisio",
"crdate": "2022-01-17T12:40:03.430Z",
"modified": "2022-01-17T12:40:03.430Z"
},
{
"_id": "2",
"name": "LoRaWAN",
"crdate": "2022-01-17T12:40:33.848Z",
"modified": "2022-01-17T12:40:33.848Z"
},
{
"_id": "3",
"name": "Kommunale Beziehungen",
"crdate": "2022-01-19T15:17:10.094Z",
"modified": "2022-01-19T15:17:10.094Z"
},
{
"_id": "4",
"name": "Test",
"crdate": "2022-03-31T13:29:41.799Z",
"modified": "2022-03-31T13:29:41.799Z"
}
],
"serviceState": {
"1": [
1,
0,
0,
1,
0,
0,
0,
1
],
"2": [
1,
0,
0,
0,
0,
0,
0,
1
],
"4": [
1,
0,
0,
0,
0,
0,
0,
1
]
}
}');
echo json_encode($json);
die();
}
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);
i have the following response, how to sort it depending on the distnace
{
"Message": "Done.",
"Status": true,
"InnerData": [
{
"id": 66,
"name": "tito",
"distance": 74,
},
{
"id": 67,
"name": "liver pool",
"distance": 83
},
{
"id": 67,
"name": "Text",
"distance": 72
}
]
}
i tried the usort but i didn't make it.
i also tried this answer here but it seems to be different than the one i need
In pure PHP 7
<?php
$json = '{
"Message": "Done.",
"Status": true,
"InnerData": [
{
"id": 66,
"name": "tito",
"distance": 74
},
{
"id": 67,
"name": "liver pool",
"distance": 83
},
{
"id": 67,
"name": "Text",
"distance": 72
}
]
}';
$array = json_decode($json, true);
usort($array['InnerData'], function($a, $b) {
return $a['distance'] <=> $b['distance'];
});
print_r($array);
As #hdifen suggested, if you're using Laravel it's a breeze to do this.
$json = '{
"Message": "Done.",
"Status": true,
"InnerData": [
{
"id": 66,
"name": "tito",
"distance": 74
},
{
"id": 67,
"name": "liver pool",
"distance": 83
},
{
"id": 67,
"name": "Text",
"distance": 72
}
]
}';
$data = json_decode($json, true);
$data['InnerData'] = collect($data['InnerData'])->sortBy('distance', SORT_REGULAR, true);
$encoded = json_encode($data);
echo $encoded;
Output:
{
"Message":"Done.",
"Status":true,
"InnerData":{
"1":{
"id":67,
"name":"liver pool",
"distance":83
},
"0":{
"id":66,
"name":"tito",
"distance":74
},
"2":{
"id":67,
"name":"Text",
"distance":72
}
}
}
Json is mainly used as a common format for sending data.
In Laravel you can convert a json object to a php array easily by using json_decode().
$phpArray = json_decode($json);
From here you can convert it to a collection to take advantage of laravels collection functions.
$laravelArray = collect($phpArray);
After this take a look at https://laravel.com/docs/5.5/collections to do sort/filter or do whatever you want to the array.
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);
}
}
}
}
}