I am going to be receiving a JSON object via HTTP POST and I am finding it difficult to parse it. This is what the JSON object looks like:
{ login: {username: 123, password: 456} }, questions:[{ name: "insomnia", type: "boolean", problem: true, question: "Did you experience insomnia?", answer: null},{ name: "go-to-bed", type: "amount", problem: false, question: "When did you go to bed?", answer: null }]}
I want to parse it into 3 different variables $username, $password and $q
From the example, this is what I expect it to be:
echo $username // **output:** 123
echo $password // **output:** 456
echo $q //**output:** questions:[{ name: "insomnia", type: "boolean", problem: true, question: "Did you experience insomnia?", answer: null},{ name: "go-to-bed", type: "amount", problem: false, question: "When did you go to bed?", answer: null }]
First your example is not a valid json. Here the valid one:
[{
"login": {
"username": 123,
"password": 456
},
"questions": [{
"name": "insomnia",
"type": "boolean",
"problem": true,
"question": "Did you experience insomnia?",
"answer": null
}, {
"name": "go-to-bed",
"type": "amount",
"problem": false,
"question": "When did you go to bed?",
"answer": null
}]
}]
Next you can use json_decode from a string:
$x = '[{
"login": {
"username": 123,
"password": 456
},
"questions": [{
"name": "insomnia",
"type": "boolean",
"problem": true,
"question": "Did you experience insomnia?",
"answer": null
}, {
"name": "go-to-bed",
"type": "amount",
"problem": false,
"question": "When did you go to bed?",
"answer": null
}]
}]';
$q = json_decode($x);
print_r($q);
echo $q[0]->login->username;
The JSON in the example is invalid, I fixed it and put together a test, I think this is what you're looking for.
<?php
$json = <<<JSON
{
"login": {
"username": 123,
"password": 456
},
"questions": [
{
"name": "insomnia",
"type": "boolean",
"problem": true,
"question": "Did you experience insomnia?",
"answer": null
},
{
"name": "go-to-bed",
"type": "amount",
"problem": false,
"question": "When did you go to bed?",
"answer": null
}
]
}
JSON;
$decoded = json_decode($json);
$username = $decoded->login->username;
$password = $decoded->login->password;
// Re-encode questions to a JSON string
$q = json_encode($decoded->questions);
echo $username."\n";
echo $password."\n";
echo $q."\n";
Related
I need to somehow handle the following recursive log output using PHP, creating an array or encoding it in json, the ultimate goal is to retrieve the "id" value of each getusers section, i've done some tests but i can't get a good result.
This is just a portion of the log string containing all the getusers sections(there can be thousands):
getusers: {
"user": {
"id": 1569976517,
"type": "user",
"first_name": "Mike",
"username": "MikesNick",
"verified": false,
"restricted": false,
"status": {
"_": "userStatusRecently"
},
"access_hash": -7018287513210933137,
"bot_nochats": false
},
"date": 1613450429,
"role": "user"
}
getusers: {
"user": {
"id": 717418136,
"type": "user",
"first_name": "John",
"last_name": "Smith",
"username": "JhonsNick",
"verified": false,
"restricted": false,
"status": {
"_": "userStatusOffline",
"was_online": 1613230815
},
"access_hash": 1814429223003924316,
"bot_nochats": false
},
"date": 1613245788,
"role": "user"
}
What is the best way to manage it and recover the data I need?
I found a way to extract the IDs from the log using the following code
$exploded = explode("getusers:",$logString);
foreach($exploded as $group){
$decoded = json_decode($group,true);
echo $decoded["user"]["id"]."<br/>";
}
I need help regarding the returned error after initiating request:
Here's the request body:
{
"name": "Test Leads",
"id": "2",
"type": "Event",
"active": true,
"eventDetails": {
"eventConditions": [
{
"type": "Category",
"comparisonType": "EQUAL",
"expression": "Leads"
},
{
"type": "ACTION",
"comparisonType": "EQUAL",
"expression": "Create"
}
],
"useEventValue": true
}
}
Error:
{"error":{
"errors":[
{"domain":"global","reason":"backendError","message":"Backend Error"}
],
"code":500,
"message":"Backend Error"
}
}
Expected Goal Details when successfully posted:
https://www.screencast.com/t/5QOJ28Tnk
Can someone check the code and see what's wrong or missing?
Thanks.
"name": "Test Leads",
"kind": "analytics#goal",
"id": "2",
"type": "Event",
"active": true,
"eventDetails": {
"eventConditions": [
{
"type": "CATEGORY",
"matchType": "EXACT",
"expression": "Leads"
},
{
"type": "ACTION",
"matchType": "EXACT",
"expression": "Create"
}
],
"useEventValue": true
}
}```
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'];
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"]
I need your help..I would like to call a json value using a json value...
here's my sample json...
first json:
{
"first_name": "Richard Catibog",
"last_name": "",
"display_name": "Richard Catibog ",
"roles": {
"owner": false,
"administrator": true
},
"login_count": 108,
"enabled": true,
"departments": [
1817719575,
1817719887,
1817722991
],
"id": 4142095,
"last_login": "2017-07-12T10:03:57Z",
"create_date": "2017-04-28T12:09:57Z",
"email": "richard.catibog+21757948948#51talk.com"
},
{
"first_name": "Rovi Cruz",
"last_name": "",
"display_name": "Rovi Roy Cruz ",
"roles": {
"owner": false,
"administrator": true
},
"login_count": 98,
"enabled": true,
"departments": [
1817719575,
1817719887,
1817722991
],
"id": 4225009,
"last_login": "2017-07-13T00:37:27Z",
"create_date": "2017-06-05T06:15:49Z",
"email": "rovi.cruz+21821290968#51talk.com"
}
Second json:
[
{
"description": "Fees Support for American Academy",
"settings": {
},
"enabled": false,
"id": 1817719575,
"name": "AA Fees Support [L2]"
},
{
"description": "American Academy",
"settings": {
},
"enabled": true,
"id": 1817722991,
"name": "Lesson and Fee Support"
},
{
"description": "Technical Support",
"settings": {
},
"enabled": true,
"id": 1817719887,
"name": "Technical Support"
}
]
I would like to call the id on the second and echo the names using the departments id list on first json...
here's what i get...
but the result that i want to see is AA Fees Support [L2], Lesson and Fee Support and Technical Support...
thank you, hope you can help me...
In this I made an array $desc that is keyed on the departments id numbers so you can easily convert the id to a Descrition
$js1 = '{
"first_name": "Richard Catibog", "last_name": "",
"display_name": "Richard Catibog ",
"roles": { "owner": false,"administrator": true},
"login_count": 108,"enabled": true,
"departments": [1817719575,1817719887,1817722991],
"id": 4142095,"last_login": "2017-07-12T10:03:57Z",
"create_date": "2017-04-28T12:09:57Z",
"email": "richard.catibog+21757948948#51talk.com"
}';
$js2 = '[
{
"description": "Fees Support for American Academy",
"settings": {},"enabled": false,"id": 1817719575,
"name": "AA Fees Support [L2]"
},
{
"description": "American Academy",
"settings": {},"enabled": true,"id": 1817722991,
"name": "Lesson and Fee Support"
},
{
"description": "Technical Support",
"settings": {},"enabled": true,"id": 1817719887,
"name": "Technical Support"
}
]';
$first = json_decode($js1);
//print_r($first);
$second = json_decode($js2);
//print_r($second);
// make array key'd on the id
$desc = [];
foreach ($second as $s) {
$desc[$s->id] = $s;
}
print_r($desc);
// go through all the dept id's in the first array
// getting a matching desctipyion from array 2
foreach ( $first->departments as $dept) {
echo $desc[$dept]->description . PHP_EOL;
}
UPDATE: After the first json data structure got changed to an array of objects
NOTE I changed your first json data structure to make it valid JSON by adding [] around the 2 objects to make a valid JSON data structure i.e. an array of objects.
All you need to do in this case is add a loop to lop over the now array of objects.
$js1 = '[{
"first_name": "Richard Catibog",
"last_name": "",
"display_name": "Richard Catibog ",
"roles": { "owner": false, "administrator": true },
"login_count": 108,
"enabled": true,
"departments": [ 1817719575, 1817719887, 1817722991 ],
"id": 4142095,
"last_login": "2017-07-12T10:03:57Z",
"create_date": "2017-04-28T12:09:57Z",
"email": "richard.catibog+21757948948#51talk.com"
},
{
"first_name": "Rovi Cruz",
"last_name": "",
"display_name": "Rovi Roy Cruz ",
"roles": { "owner": false, "administrator": true },
"login_count": 98,
"enabled": true,
"departments": [ 1817719575, 1817719887, 1817722991 ],
"id": 4225009,
"last_login": "2017-07-13T00:37:27Z",
"create_date": "2017-06-05T06:15:49Z",
"email": "rovi.cruz+21821290968#51talk.com"
}]';
$js2 = '[
{
"description": "Fees Support for American Academy",
"settings": {},"enabled": false,"id": 1817719575,
"name": "AA Fees Support [L2]"
},
{
"description": "American Academy",
"settings": {},"enabled": true,"id": 1817722991,
"name": "Lesson and Fee Support"
},
{
"description": "Technical Support",
"settings": {},"enabled": true,"id": 1817719887,
"name": "Technical Support"
}
]';
$first = json_decode($js1);
//print_r($first);
$second = json_decode($js2);
//print_r($second);
// make array key'd on the id
$desc = [];
foreach ($second as $s) {
$desc[$s->id] = $s;
}
//print_r($desc);
//Loop through all the first array of object
foreach ( $first as $f) {
// go through all the dept id's in the first array
// getting a matching desctipyion from array 2
foreach ( $f->departments as $dept) {
echo $desc[$dept]->description . PHP_EOL;
}
echo PHP_EOL;
}
RESULT
Fees Support for American Academy
Technical Support
American Academy
Fees Support for American Academy
Technical Support
American Academy
here you go
$json1 = '{
"first_name": "Richard Catibog",
"last_name": "",
"display_name": "Richard Catibog ",
"roles": {
"owner": false,
"administrator": true
},
"login_count": 108,
"enabled": true,
"departments": [
1817719575,
1817719887,
1817722991
],
"id": 4142095,
"last_login": "2017-07-12T10:03:57Z",
"create_date": "2017-04-28T12:09:57Z",
"email": "richard.catibog+21757948948#51talk.com"
}
';
$json2 ='[
{
"description": "Fees Support for American Academy",
"settings": {
},
"enabled": false,
"id": 1817719575,
"name": "AA Fees Support [L2]"
},
{
"description": "American Academy",
"settings": {
},
"enabled": true,
"id": 1817722991,
"name": "Lesson and Fee Support"
},
{
"description": "Technical Support",
"settings": {
},
"enabled": true,
"id": 1817719887,
"name": "Technical Support"
}
]';
$json1 = json_decode($json1, true);
$json2 = json_decode($json2, true);
$department = function($id) use($json2) {
foreach($json2 as $dep) {
if($dep["id"] == $id) {
return $dep;
}
}
return false;
};
foreach($json1["departments"] as $id) {
$dep = $department($id);
if(is_array($dep)) {
echo sprintf("id: %s, name: %s\n", $id, $dep["name"]);
}
}