I am returning json response to api, using json_encode() method.
I have array which is where a key users can have multiple user or no user i.e empty array,and key course is either empty or can have single object as below
{
"success": true,
"code": 200,
"message": "",
"result": {
"users": [],
"course": []
}
}
if it has data the response is like this
{
"success": true,
"code": 200,
"message": "",
"result": {
"users": [
{
"name": "Vishal",
"Age": 25
},
{
"name": "Akshay",
"Age": 29
}
],
"course": {
"name": "xyz"
}
}
}
but what i want is users should be array in both cases and course should return as object in both cases. is it possible.??
You can force course entry to be object before json encoding.
$ret["result"]["course"] = (object)$course;
Related
I have this JSON payload below and want to get names and ids from the payload. However, l cannot object names and ids from the payload.
Decode JSON
$result = json_decode($resp->getBody()->getContents(), true);
return response()->json(
[
"code" => 200,
"message" => "OK",
"payload"=> $result['payload'] ?? '',
]);
Api json payloads
{
"code": 200,
"message": "OK",
"payload": {
"items": [
{
"name": "Hostel",
"image": {
"name": "WEWEBBFC791FD50E347BD.jpeg"
},
"rate": {
"amount": "3.0000",
"currency": {
"code": "US"
}
},
"pricing": [
{
"rate": "3.0000"
}
],
"id": 12, // get this id
"created_at": "2021-02-28T11:08:25+00:00"
}
..........
],
"total": 10,
"offset": 10
}
}
Use json_decode to decode the json to an associative array, then access the elements of the array as you would any other assoc array.
It looks as though you can have one or more items in your collection, so you'll want to use a loop to iterate over them.
$decoded = json_decode($json, true);
foreach ($decoded['payload']['items'] as $item) {
$name = $items['name'];
$id = $items['id'];
dump($name, $id);
}
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 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);
}
}
}
}
}
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 am trying to decode following JSON file
{
"email": "mail#gmail.com",
"password": "12345",
"languageProficiency": {
"language": "English",
"proficiency": 4
},
"tags": [
{
"name": "singing"
},
{
"name": "dance"
}
]
}
When I do this
$data = json_decode($jsonContent, true);
echo $data;
die();
I have following error:
Array value found, but an object is required
Question
1) How can I view data from JSON
2) How can I access property of each object in tags array
I am validating Json content againsts this schema
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"email": {
"type": "string"
},
"password": {
"type": "string"
},
"languageProficiency": {
"type": "object",
"properties": {
"language": {
"type": "string"
},
"proficiency": {
"type": "integer"
}
},
"required": [
"language",
"proficiency"
]
},
"tags": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string"
}
},
"required": [
"name"
]
}
}
},
"required": [
"email",
"password",
"languageProficiency",
"tags"
]
}
UPDATE
I tried following to view json content
print_r($data)
But I still get same error
$data = json_decode($jsonContent, true);
Above line of code will return Array, for which you can not use echo directly to print an array.
To print specific value of an array (e.g. email), do it like this:
echo $data["email"];
Tip:
Use print_r() to know the array structure like this,
echo "<pre>";
print_r($data);
you can try print_r($data) to explore values