This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
I'm new into PHP and JSON and I have a problem, I want to retrieve a item and value from a JSON:
{
"status": true,
"webhook_type": 100,
"data": {
"product": {
"id": "lSEADIQ",
"attachment_id": null,
"title": "Registration",
"description": null,
"image": null,
"unlisted": false,
"type": "service",
"price": 1,
"currency": "EUR",
"email": {
"enabled": false
},
"stock_warning": 0,
"quantity": {
"min": 1,
"max": 1
},
"confirmations": 1,
"custom_fields": [
{
"name": "Forum username",
"type": "text",
"required": true
}
],
"gateways": [
"Bitcoin"
],
"webhook_urls": [],
"dynamic_url": "",
"position": null,
"created_at": "2018-10-01 12:51:12",
"updated_at": "2018-10-01 12:55:46",
"stock": 9223372036854776000,
"accounts": []
},
"order": {
"id": "8e23b496-121a-4dc6-8ec4-c45835680db2",
"created_at": "Tue, 02 Oct 2018 00:54:56 +0200",
"paid_at": null,
"transaction_id": null,
"confirmations": 1,
"required_confirmations": 3,
"received_amount": 0,
"crypto_address": "1NeNQws7JLbTr6bjekfeaXSV7XiyRsv7V8",
"crypto_amount": "0.4815",
"quantity": 1,
"price": 19.99,
"currency": "EUR",
"exchange_rate": "1.21",
"gateway": "BTC",
"email": "webhook#site.gg",
"ip_address": "123.456.789.111",
"agent": {
"geo": {
"ip": "214.44.18.6",
"iso_code": "US",
"country": "United States"
},
"data": {
"is_mobile": false,
"is_table": false,
"is_desktop": true,
"browser": {
"name": "Chrome",
"version": "63.0.3239.132"
}
}
},
"custom_fields": [
{
"name": "user_id",
"value": 184191
}
],
"user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3)"
}
}
}
I want to retrieve items from data -> order, for example "id" or "ip_address".
Thank you for read this, I hope someone can help me in this, because I'm lost, I started to code very recently and I'm trying to learn a lot.
Regards!
Where test.json is the json you uploaded, place it in a file named test.json and ensure its placed in the same directory.
<?php
$load = file_get_contents("test.json") or die("JSON load failed");
$json_a = json_decode($load, true);
print $json_a['data']['order']['ip_address'] . "\n";
?>
Gives:
123.456.789.111
My answer reads the JSON from a file as were it dumped directly in your code, which indeed it could be, it would make the code less readable and your file more messy.
If you dont want to place the file in the same directory, simply specify the full file path. E.g. file_get_contents("this/dir/here/test.json");
You can read about how json_decode works here, its essential we pass it the true parameter to make our arrays associative.
You can extract your need array from JSON data. You can use a loop too to read all your data inside the order array.
$array = json_decode($json, true);
$verbose = $array['data'];
$orderArray = $verbose['order'];
print_r($orderArray);
echo $orderArray['id'];
echo $orderArray['ip_address'];
Related
I have a project in laravel which has API. I'm asking the API for posts(I call them recommendation).
Now my api response look like this -
{
"success": true,
"data": {
"current_page": 1,
"data": [
{
"id": 3,
"course_id": "20",
"title": "Dormouse followed.",
"description": "Alice aloud, addres
"file": "https://example.com/storage/images/2019/10/01/phTJ.png",
"created_at": null,
"updated_at": "2019-10-01 14:21:46",
"recommendation_likes": 0,
"is_bookmarked": "true",
"is_liked": "false",
"likes_count": []
}
...
...
...
All is good but I don't wanna likes_count to be in the result. It is a relation method. I get from it all I need. It is if the user liked this post. And it is is_liked in the result . but likes_count automatically added to the response .
if($item->likesCount->contains($user->id)){
$item['is_liked']='true';
}
I tried delete it with
foreach ($recommendations as $item) {
unset($item['likes_count']);
}
But it doesn't do it.
I think the problem is how you are referencing the object data structure. You are attempting to unset() something that doesn't exist so no error is thrown but the likes_count isn't getting removed either.
Here's your code example (fixed and modified for demonstration):
<?php
$apiResult = <<<eod
{
"success": true,
"data": {
"current_page": 1,
"data": [
{
"id": 3,
"course_id": "20",
"title": "Dormouse followed.",
"description": "Alice aloud, addres",
"file": "https://example.com/storage/images/2019/10/01/phTJ.png",
"created_at": null,
"updated_at": "2019-10-01 14:21:46",
"recommendation_likes": 0,
"is_bookmarked": "true",
"is_liked": "false",
"likes_count": []
},
{
"id": 4,
"course_id": "20",
"title": "Dormouse followed.",
"description": "Alice aloud, addres",
"file": "https://example.com/storage/images/2019/10/01/phTJ.png",
"created_at": null,
"updated_at": "2019-10-01 14:21:46",
"recommendation_likes": 0,
"is_bookmarked": "true",
"is_liked": "false",
"likes_count": []
}
]
}
}
eod;
$result = json_decode($apiResult);
$data = $result->data->data;
var_dump($data);
// This should remove the likes_count array from the $result structure.
foreach ($data as &$item) {
unset($item->likes_count);
}
var_dump($data);
A quick way would be to make that 'attribute' (relation) hidden:
$recommendations->makeHidden('likes_count');
Though I am not sure how you are building your response.
Need help with the following I writing a webhook in php, and need the ability to read the context parameters.
Can someone help me to understand how it can be done?
Here is my example JSON:
{
"id": "6e774dc2-2323-42b3-bd3c-ab64930f8b92",
"timestamp": "2017-12-22T21:12:19.094Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "Yes",
"action": "Triage.Triage-yes",
"actionIncomplete": false,
"parameters": {},
"contexts": [
{
"name": "triage-followup",
"parameters": {
"triagecriteria": [],
"roomEntity.original": "",
"roomname": "300",
"roomnames.original": "living",
"roomid": "200",
"context": "",
"roomnames": [
"living"
],
"counter": "400",
"roomEntity": "100",
"triagecriteria.original": ""
},
"lifespan": 3
}
],
"metadata": {
"intentId": "ecd4a2e5-65a0-41b2-ac72-edcf4d2e73f2",
"webhookUsed": "true",
"webhookForSlotFillingUsed": "false",
"webhookResponseTime": 203,
"intentName": "Triage - yes"
},
"fulfillment": {
"speech": "Yes",
"source": "agent",
"displayText": "No",
"messages": [
{
"type": 0,
"speech": "Yes"
}
]
},
"score": 1
},
"status": {
"code": 200,
"errorType": "success",
"webhookTimedOut": false
},
"sessionId": "db8c1a4e-fa0c-4257-a536-78b63879eef9"
}
I want to be able to refer to [results][Contexts][Parameters]
I am using
$update_response = file_get_contents("php://input");
$update = json_decode($update_response, true, 512, JSON_BIGINT_AS_STRING);
and trying to access the value as $update["results"]["Contexts"]["Parameters"]["roomid"]
The names are case sensitive, and you need to be careful about trailing "s"es. Since some of the items are numerically indexed arrays, you'll need to include that as part of the index. Try
$update["result"]["contexts"][0]["parameters"]["roomid"]
Could someone help me think of a smart algorithm?
Problem
JSON data looks kinda like this (can't give the real data :/):
{
"$id": "1",
"Start": 1000,
"End": 1200,
"Account": {
"$id": "2",
"id": "af51f511-e851-4d01-808b-2fa3c070d3ad",
"aLotMoreInfo": "cool",
"Parents": {
"$id": "3",
"id": "73d7a1f1-82e8-4a7e-bccb-838a251e1a38",
"aLotMoreInfo": "notcool",
"Parents": null,
"Children": {
"ref": 2
}
},
"Children": null
}
}
Anyways the problem now is that it contains ref with a value behind it. The above JSON should be like this:
{
"$id": "1",
"Start": 1000,
"End": 1200,
"Account": {
"$id": "2",
"id": "af51f511-e851-4d01-808b-2fa3c070d3ad",
"aLotMoreInfo": "cool",
"Parents": {
"$id": "3",
"id": "73d7a1f1-82e8-4a7e-bccb-838a251e1a38",
"aLotMoreInfo": "notcool",
"Parents": null,
"Children": {
"$id": "2",
"id": "af51f511-e851-4d01-808b-2fa3c070d3ad",
"aLotMoreInfo": "cool",
"Parents": {
"$id": "3",
"id": "73d7a1f1-82e8-4a7e-bccb-838a251e1a38",
"aLotMoreInfo": "notcool",
"Parents": null,
"Children": null
},
"Children": null
},
"Children": null
}
}
}
I need to know two things:
how to easily get the JSON data which has been stated before
how do I copy it but set the value Children to null every single
time?
I hope someone know a good way how this can be done, because I can't really think of a clever way...
I have the following response (I cut the extra short):
{
"meta": {
"current_page": "1",
"last_page": "1",
"per_page": "15",
"total": "1",
"from": "1",
"to": "1"
},
"Products": [
{
"archived": "0",
"committed_stock": "0",
"created_at": "2015-05-10T17:39:53+00:00",
"deleted": "0",
"description": "desc",
"id": "43061710",
"links": {
"Users": [
{
"id": "107534",
"type": "created_by"
}
],
"Attributes": [
{
"id": "31538870"
}
]
}
}
]
}
Everytime I get this response, there will only be one item in "Attributes." What is the easiest way of grabbing this value? So far I have this:
$json = json_decode($json_data);
$json = json_decode($json_data, true);
echo $json["Products"][0]["links"]["Attributes"][0]["id"];
try this:
var_dump( $json->Products[0]->links->Attributes);
the object field could be ether also an object, or an array:
refer to field: $object->object
refer to array's i cell: $object->array[i]
P.S.
please edit the json, it's missing it's end...
You may also want to try some JSON Path libs for PHP: https://github.com/Peekmo/JsonPath
I am managed to get tokens and using token to get the content from box.com site. I seen with other site like drop box,smug mug gives many versions of URL of images but here I am not seeing when I pull using the below command
https://www.box.com/api/2.0/folders/0?access_token= and the result is below.
I want to know the path of an image 20131228_181031.jpg in below data, I want to pull the image using php file_getcontent command for which I need image path.
{
"type": "folder",
"id": "0",
"sequence_id": null,
"etag": null,
"name": "All Files",
"created_at": null,
"modified_at": null,
"description": "",
"size": 9985219,
"path_collection": {
"total_count": 0,
"entries": []
},
"created_by": {
"type": "user",
"id": "",
"name": "",
"login": ""
},
"modified_by": {
"type": "user",
"id": "207866808",
"name": "praveen",
"login": " my id"
},
"trashed_at": null,
"purged_at": null,
"content_created_at": null,
"content_modified_at": null,
"owned_by": {
"type": "user",
"id": "207866808",
"name": "Chandler",
"login": "email#tbl.com"
},
"shared_link": null,
"folder_upload_email": null,
"parent": null,
"item_status": "active",
"item_collection": {
"total_count": 5,
"entries": [
{
"type": "file",
"id": "12673472942",
"sequence_id": "0",
"etag": "0",
"sha1": "a43eceb5de8ea1334aa545c95e92d7527f7bf163",
"name": "20131228_181031.jpg"
},
{
"type": "file",
"id": "12673467202",
"sequence_id": "0",
"etag": "0",
"sha1": "dfce2896cd97856fbe2755ec5b7e344103181e87",
"name": "20131228_181034.jpg"
},
{
"type": "file",
"id": "12673477676",
"sequence_id": "0",
"etag": "0",
"sha1": "dee70d192fc6bfec538d5581f8460005d7a79155",
"name": "20131228_181938.jpg"
},
{
"type": "file",
"id": "12673481562",
"sequence_id": "0",
"etag": "0",
"sha1": "a07e7c970ed0aa7fdab955aaad0d4e245d1595cd",
"name": "20131228_181943.jpg"
},
{
"type": "file",
"id": "12673486582",
"sequence_id": "0",
"etag": "0",
"sha1": "156446b911a22604b2a0c032888b4d7a6b6a3bfd",
"name": "20131228_181957.jpg"
}
],
"offset": 0,
"limit": 100,
"order": [
{
"by": "type",
"direction": "ASC"
},
{
"by": "name",
"direction": "ASC"
}
]
}
}
On the Box API, when requesting a file, you do not need to know the folder it is in and so you do not need to build the path. You just make the request with the file id and include your access token in the header. For more info see the getting started docs here.
A quick example using file_get_contents is below:
<?php
$fileId = 12673472942;
$accessToken = 'YOURACCESSTOKENGOESHERE';
$sBox = stream_context_create(array(
'http'=> array(
'header' => "Authorization: Bearer $accessToken\r\n"
)
));
$fileData = file_get_contents(
"https://api.box.com/2.0/files/$fileId/content",
false,
$sBox
);
var_dump($fileData);
The $fileId is the "id" field in the JSON data you provided, so for the file you need it would be 12673472942.
Hope that helps.