I have a nested json file
{
"event_type": "INCOMING_BTC",
"event_uid": "5515c5601f7b3",
"datetime": "2015-03-27 21:02:37",
"resources": [
{
"resource_type": "transaction",
"resource": {
"id": 105062,
"datetime": "2015-03-27 21:02:23",
"description": "Money from Xapo Tip",
"order_type": "payment_received",
"from": {
"type": "btc_address",
"id": "1AqF787aPHgPRZ81kdQSeEwW46yjyrAaxR"
},
"to": {
"destination_type": "btc_address",
"destination_id": "1N65Bz88zKUDPKhUUsx8f9Qwsuo96Hqz7S",
"to_account": 1276
},
"generic_type": "credit",
"amount": "0.0000001",
"currency": "BTC",
"status": "completed",
"txConfidence": 1,
"rejection_reason": null,
"notes": null,
"base_currency": "USD",
"exchange_rate": null,
"exchange_amount": null
}
},
{
"resource_type": "address",
"resource": {
"id": "1N65Bz88zKUDPKhUUsx8f9Qwsuo96Hqz7S",
"address": "1N65Bz88zKUDPKhUUsx8f9Qwsuo96Hqz7S",
"meta_data": null,
"label": null,
"total_received": "0.00000350",
"created_at": "2015-03-08 14:50:59",
"address_type": "multisig",
"id_account": "1276"
}
}
]
}
And I have saved this file in public folder with name xapojson.txt
In my routes file I have done json_decode to decode this data to a variable 'transaction' and passed it to view
Route::get('/', function () {
$transaction = json_decode(file_get_contents('xapojson.txt'));
return view('transaction', compact('transaction'));
});
Now in transaction view I have to display the data from this nested json.
I have tried out lots of variation and searched on google and stackoverflow but nothing worked.
I found this somewhat helpful Check this out. But it also do not get into more nesting.
In the view I have to display these datas:-
resources[0]->resource->from->type
resources[0]->resource->id
resources[0]->resource->from->id
resources[0]->resource->status
resources[0]->resource->amount
resources[0]->resource->currency
resources[0]->resource->to->destination_id
datetime
Please help me on displaying the above fields.
Try using
$transaction = json_decode(file_get_contents('xapojson.txt'), true);
Well when I made this code work in simple php, I extracted the data by
$xapo_json = file_get_contents('xapojson.txt');
$xapo_json_decoded = json_decode($xapo_json);
$from_type = $xapo_json_decoded->resources[0]->resource->from->type;
$transacid = $xapo_json_decoded->resources[0]->resource->id;
$from = $xapo_json_decoded->resources[0]->resource->from->id;
$status = $xapo_json_decoded->resources[0]->resource->status;
$amount = $xapo_json_decoded->resources[0]->resource->amount;
$currency = $xapo_json_decoded->resources[0]->resource->currency;
$to = $xapo_json_decoded->resources[0]->resource->to->destination_id;
$datetime = $xapo_json_decoded->datetime;
Then in the routes file i changed
return view('transaction', compact('transaction'));
to
return View::make('transaction')->with('transaction',$transaction);
And in view I used this
{{ $transaction->resources[0]->resource->from->id }}
Voila, It works
you can do it with the below code ( am taking div as example you can change it to table or whatever
#foreach($transaction->resources as $resource)
#if(is_set($resource->from))
<div>{{$resource->from->type}}</div>
#endif
<div>{{$resource->id}}</div>
#if(is_set($resource->from))
<div>{{$resource->from->id}}</div>
#endif
<div>{{$resource->status}}</div>
<div>{{$resource->amount}}</div>
<div>{{$resource->currency}}</div>
<div>{{$resource->to->destination_id}}</div>
#endforeach
Related
The task is to fetch json user data from an api and store it in array. Then be able to make changes to it different routes.
Here is a sample of the data from the api, they are 10 in total and in an array.
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna#melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
},
i fetched the data using this:
$jsonurl = "http://jsonplaceholder.typicode.com/users";
$json = file_get_contents($jsonurl);
global $userData;
$userData = json_decode($json);
I displayed the data in a /users route with this
Route::get('/users', function(){
global $userData;
echo json_encode($userData);
});
I was told to get set a /delete route that deletes the last object from the array.
Route::get('/delete', function(){
global $userData;
$lastObjIndex = count($userData) -1;
array_splice($userData, $lastObjIndex,1);
//print_r('last user deleted');
echo json_encode($userData);
$userData = $userData;
});
The problem is that the delete route does not only works once(it does not delete subsequent last objects and returns the same thing when the route is accessed again) and does not show any change in when i access the users route. The data isn't stored in the server.
I feel there is something i don't know about that could help with this. Any suggestion would be appreciated.
I'm storing dynamic data in a MySQL JSON field using Laravel v6.11.0, nova v2.9.3 and nova-flexible-content v0.1.13. The data stored looks similar to this:
[
{
"layout": "source",
"key": "5ce8e0a877487fe5",
"attributes": {
"value": "342",
"unit": "USD",
"language": "en",
"url": "http:\\/\\/google.com",
"authority": "google.com",
"entry_date": "2020-01-21",
"date": "2019-12-21"
}
},
{
"layout": "source",
"key": "a82393ce016e8c14",
"attributes": {
"value": "444",
"unit": "USD",
"language": "en",
"entry_date": "2020-01-21",
"url": "https:\\/\\/google.com",
"authority": "TEST",
"date": "2020-01-20"
}
}
]
I was wondering if it's possible to build a Laravel Query to select the second entry based on the authority entry? Criteria are:
url should contain google.com AND
authority shouldn't be google.com
I've found https://laravel.com/docs/5.8/queries#json-where-clauses, but am struggling to put the right query together. Maybe someone could give me some pointers on how to do it? Thank you
You may refer to this discussion on Laracast
$data = App\YourModel::whereRaw('JSON_CONTAINS(body->"$[*].attributes.url", "\"https://google.com\"")')
->orWhereRaw('JSON_CONTAINS(body->"$[*].id", "\"http://google.com\"")')
->whereRaw('not JSON_CONTAINS(body->"$[*].attributes.authority", "\"google.com\"")')
->get();
foreach ($data as $key => $row) {
$bodyArr = json_decode($row->body);
foreach ($bodyArr as $item) {
if ((preg_match("/(http:\/\/www\.|https?:\/\/google.com)/i",$item->attributes->url)) && (strpos($item->attributes->authority, 'google.com') === false)) {
dump($item);
// YOUR CODE GOES HERE
}
}
}
A webhook is sending me some data to the URl I have provided. I am trying to catch the data. This is the code I am using:-
if ($this->input->server('REQUEST_METHOD') == 'POST')
{
file_put_contents('test.txt', file_get_contents('php://input'));
......................
}
The data which got saved in the txt file is this:-
{
"created_at": "2017-04-04 12:03:07 UTC",
"href": "http://api.groovehq.com/v1/tickets/131",
"links": {
"customer": {
"id": "0454984580",
"href": "http://api.groovehq.com/v1/customers/ncc2017customer#gmail.com"
},
"drafts": {
"href": "http://api.groovehq.com/v1/tickets/131/drafts"
},
"state": {
"href": "http://api.groovehq.com/v1/tickets/131/state"
},
"messages": {
"href": "http://api.groovehq.com/v1/tickets/131/messages"
}
},
"number": 131,
"priority": "low",
"resolution_time": null,
"state": "unread",
"title": "gh",
"updated_at": "2017-04-04 12:03:07 UTC",
"system_updated_at": "2017-04-04 12:03:07 UTC",
"assigned_group_id": null,
"assigned_group": null,
"closed_by": null,
"tags": [
],
"mailbox": "Inbox",
"mailbox_id": "1923237790",
"message_count": 1,
"summary": "Complaint Date: 2017-4-22 Service Provider: Airtel Type of Complaint: Billing NCC need to do: Investigate and resolve the issue Complaint Details: Vb",
"type": "API",
"snoozed_until": null,
"last_message": "Complaint Date: 2017-4-22<br />\nService Provider: Airtel<br />\nType of Complaint: Billing<br />\nNCC need to do: Investigate and resolve the issue<br />\nComplaint Details: Vb",
"assignee": null,
"app_url": "https://matrixdroid.groovehq.com/groove_client/tickets/44746020",
"app_customer_url": "https://matrixdroid.groovehq.com/groove_client/contacts/customers/17295897",
"customer_name": "ncc2017customer#gmail.com",
"last_message_plain_text": "Complaint Date: 2017-4-22\nService Provider: Airtel\nType of Complaint: Billing\nNCC need to do: Investigate and resolve the issue\nComplaint Details: Vb"
}
Now, I need to get the links->customer->href data
How can I get this?
I tried this:-
$json_data = file_get_contents('php://input');
$json_decode_data = json_decode($json_data);
file_put_contents('test.txt', $json_decode_data['links']['customer']['href']);
Nothing getting written in the txt file. How can I parse the href data?
json_decode() will produce a StdClass by default. If you want an array, add a true parameter. Then use the correct variable, being $data, when referencing it:
$data = json_decode(file_get_contents('php://input'), true);
To get data of the href, you need to do something like this
<?php
$data = json_decode(file_get_contents('test.txt'));
echo '<pre>';
print_r($data->links->customer->href);
?>
Trying to get the name of the latest Twitch-follower with help from a snipper I found online. However I get an error message which I can't understand
$json_array2 = json_decode(file_get_contents('https://api.twitch.tv/kraken/channels/'.strtolower($channelName).'/follows?limit=1'), true);
$latestFollower = $json_array2['follows']['user']['name'];
Typing in the URL in my broser I get this so I'm thinking follows->user->name should be right but I guess not :(
{
"follows": [
{
"created_at": "2014-07-09T23:30:59Z",
"_links": {
"self": "https://api.twitch.tv/kraken/users/username17376/follows/channels/sodapoppin"
},
"user": {
"_id": 65845277,
"name": "username17376",
"created_at": "2014-07-08T03:59:16Z",
"updated_at": "2014-07-08T04:14:14Z",
"_links": {
"self": "https://api.twitch.tv/kraken/users/username17376"
},
"display_name": "Username17376",
"logo": null,
"bio": null,
"type": "user"
}
}
],
"_total": 339627,
"_links": {
"self": "https://api.twitch.tv/kraken/channels/sodapoppin/follows?direction=DESC&limit=1&offset=0",
"next": "https://api.twitch.tv/kraken/channels/sodapoppin/follows?direction=DESC&limit=1&offset=1"
}
}
Should be
$json_array2['follows'][0]['user']['name'];
Based on your JSON
{
"follows": [
{
Which shows that follows is an array. The first object in the the array (index 0) is an object that has the property "user"
As a test, this JSON data is being POSTed to my website:
{
"order": {
"id": null,
"created_at": null,
"status": "new",
"total_btc": {
"cents": 100000000,
"currency_iso": "BTC"
},
"total_native": {
"cents": 2263,
"currency_iso": "USD"
},
"custom": "123456789",
"button": {
"type": "buy_now",
"name": "Test Item",
"description": null,
"id": null
},
"transaction": {
"hash": "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b",
"confirmations": 0
}
}
}
Since it is being sent server-to-server I cannot visibly see the data. I have tried sending the $_POST array to a text file, but it comes up blank. What I think I need to do is:
$data = json_decode($jsonData);
But how do I set the variable $jsonData?
You can try to use wrappers for reading raw POST query.
$data = file_get_contents("php://input");
Have you tried this, store the sting obtained to a variable and then decoding it?
$postedJsonData= '{"order":{"id":null,"created_at":null,"status":"new","total_btc":
{"cents":100000000,"currency_iso":"BTC"},"total_native":
{"cents":2263,"currency_iso":"USD"},"custom":"123456789","button":
{"type":"buy_now","name":"Test Item","description":null,"id":null},"transaction":
{"hash":"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b","confirmations":0}}}';
var_dump(json_decode($postedJsonData, true));
The true parameter would return an associative array
$data = json_decode($jsonData, True);