Getting 2nd level of JSON data in PHP - php

I have JSON data which follows this model:
{
"questions": [
{
"questionKey": 0,
"question": "string",
"required": true,
"type": "multipleChoice",
"maxSize": 0,
"answers": [
{
"answer": "string",
"answerKey": 0
}
]
}
],
"fields": [
{
"field": "string",
"answers": [
"string"
],
"required": true,
"maxSize": 0
}
]
}
I am having difficult getting all the fields > field values. When i do a var_dump($jsondata) it is printing all the data so I know I am getting and storing the data ok. I know I need to do a foreach statement like:
foreach ($jsondata as $data) {
echo $data['fields'];
}
I know this is wrong but I don't know how to cycle through all the fields > field values. Your help is much appreciated :)

Try something like this:
//Decode JSON string into a PHP array.
$jsonData = json_decode($jsonStr, true);
//Loop through it like any associative array.
foreach($jsonData['fields'] as $field){
var_dump($field);
echo $field['field'] , '<br>';
}

Related

Printing a nested JSON Array value [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 3 months ago.
I've been trying to find ways to print the individual data but can't seem to figured out where I'm going wrong.
I started with this but I get no results. Before this I tried nesting loops but also got nowhere either.
$data = curl_exec($ch);
$d = json_decode($data, true);
foreach($d as $k=>$v){
echo $v['value']['displayName'];
}
Then I tried the following with only got me some of the results. I'm not sure where I'm going wrong with this.
foreach(json_decode($data,true) as $d){
foreach($d as $k=>$v){
foreach($v as $kk=>$vv){
echo $kk.$vv;
}
}
}
The JSON looks like the following:
{
"value": [
{
"id": "",
"name": "",
"etag": "",
"type": "Microsoft.SecurityInsights/alertRules",
"kind": "Scheduled",
"properties": {
"incidentConfiguration": {
"createIncident": true,
"groupingConfiguration": {
"enabled": false,
"reopenClosedIncident": false,
"lookbackDuration": "PT5M",
"matchingMethod": "AllEntities",
"groupByEntities": [],
"groupByAlertDetails": null,
"groupByCustomDetails": null
}
},
"entityMappings": [
{
"entityType": "Account",
"fieldMappings": [
{
"identifier": "FullName",
"columnName": "AccountCustomEntity"
}
]
},
{
"entityType": "IP",
"fieldMappings": [
{
"identifier": "Address",
"columnName": "IPCustomEntity"
}
]
}
],
"queryFrequency": "P1D",
"queryPeriod": "P1D",
"triggerOperator": "GreaterThan",
"triggerThreshold": 0,
"severity": "Medium",
"query": "",
"suppressionDuration": "PT1H",
"suppressionEnabled": false,
"tactics": [
"Reconnaissance",
"Discovery"
],
"displayName": "MFA disabled for a user",
"enabled": true,
"description": "Multi-Factor Authentication (MFA) helps prevent credential compromise. This alert identifies when an attempt has been made to diable MFA for a user ",
"alertRuleTemplateName": null,
"lastModifiedUtc": "2022-11-14T02:20:28.8027697Z"
}
},
...
...
...
Here is how you can get the display name without a loop. Notice that the 0 is the key value of the array since it doesn't have a name.
We start from the value, and we move one layer deeper by selecting the first array 0. Now we need to select the properties and finally, we can get the displayName from there.
$displayName = $d["value"][0]["properties"]["displayName"];
echo($displayName);
/*
Here is a quick demonstration:
value:
{
0:
{
...
properties:
{
...
displayName: [We made it!]
}
}
}
*/
And here is a very good post that explains this in more detail
How to decode multi-layers nested JSON String and display in PHP?

PHP get JSON key value from specific object

Ive got the following JSON:
{
"servers": [
{
"id": "f34c0185-4c9e-40fd-82f6-1d6e9a5d499e",
"name": "vm01"
},
{
"id": "d671ac7d-3b5a-4777-8510-6e8e58295061",
"name": "vm02"
},
{
"id": "h59j23cc-9ve2-4508-1277-85y1lo27562m",
"name": "vm03"
}
]
}
I also have another JSON that gives me the ID I want to search for.
For example: "d671ac7d-3b5a-4777-8510-6e8e58295061".
I want to search for the JSON Object, that contains that ID and get the value of the name key. I tried with loops and if, else's but I didn't manage to get it working.
Thanks for your help!
decode the json as array object then loop through with the ID that u want to search
<?php
$json = '{
"servers": [
{
"id": "f34c0185-4c9e-40fd-82f6-1d6e9a5d499e",
"name": "vm01"
},
{
"id": "d671ac7d-3b5a-4777-8510-6e8e58295061",
"name": "vm02"
},
{
"id": "h59j23cc-9ve2-4508-1277-85y1lo27562m",
"name": "vm03"
}
]
}';
$j = json_decode($json, true);
foreach($j['servers'] as $arr)
{
if( $arr['id'] == 'd671ac7d-3b5a-4777-8510-6e8e58295061' ) echo $arr['name'];
}
demo: https://3v4l.org/0DboX

Add to a JSON object, with PHP

I'd like to increment a JSON object with a new given one but I can't do it. I have the following JSON:
{ "field_name":{ "type":"text", "visual_name":"Field Name", "required": true } }
The user will create more fields and I'd like to insert in the original JSON the new field that comes in this format:
"field_name2":{ "type":"select", "visual_name":"Field Name 2", "required": true, "options":{"opt1":"yes","opt2":"no"} }
Looks like you're trying to add new elements to the root JSON object, in which case you simply need to:
Decode the JSON objects into PHP arrays.
Merge the arrays into one.
Encode the merged array back into JSON.
$field1 = '{"field_name":{"type":"text", "visual_name":"Field Name", "required":true}}';
$field2 = '{"field_name2":{"type":"select", "visual_name":"Field Name 2", "required":true, "options":{"opt1":"yes", "opt2":"no"}}}';
$arr = array_merge(json_decode($json1, true), json_decode($json2, true));
$json = json_encode($arr);
The final $json object will be:
{
"field_name": {
"type": "text",
"visual_name": "Field Name",
"required": true
},
"field_name2": {
"type": "select",
"visual_name": "Field Name 2",
"required": true,
"options": {
"opt1": "yes",
"opt2": "no"
}
}
}
If you want to add the fields into a JSON array, rather than an object, you can do this instead:
$arr = [json_decode($json1, true), json_decode($json2, true)];
Which results in:
[
{
"field_name": {
"type": "text",
"visual_name": "Field Name",
"required": true
}
},
{
"field_name2": {
"type": "select",
"visual_name": "Field Name 2",
"required": true,
"options": {
"opt1": "yes",
"opt2": "no"
}
}
}
]
Note
If you try to add your original second field as you have given it in your question, it won't work because it's not a fully formatted JSON string. You must ensure it has the outer pair of curly braces.
Incorrect:
"field_name2":{"type":"select", "visual_name": ...}
Correct:
{"field_name2":{"type":"select", "visual_name": ...}}

Looping through a json file to find a particular value in PHP

My json file look likes
myjson.json
[
{"name":"category_01","data":
[
{"id":"1","word":"ma","given_value":"1"},
{"id":"3","word":"me","given_value":"1"},
] }
[
{"name":"category_02","data":
[
{"id":"1","word":"vea","given_value":"1"},
{"id":"3","word":"ve","given_value":"1"},
] }
So what I want here is, check whether a particular value is in this json array using php. Assume that,
myphp.php
$word = 've';
if this value is in the above array, should find is it in category_01 or category_02. and also want to find given_value of matching word.
I just tried in this way,
$data = file_get_contents ("myjson.json");
$json = json_decode($data, true);
foreach($arr as $item) {
$uses = ($item['word']= $word);
}
This doesn't work. How can I fix this, Please help me!
First of all, the JSON you posted is invalid. I think it should look like this:
[
{
"name": "category_01",
"data": [{
"id": "1",
"word": "ma",
"given_value": "1"
},
{
"id": "3",
"word": "me",
"given_value": "1"
}
]
},
{
"name": "category_02",
"data": [{
"id": "1",
"word": "vea",
"given_value": "1"
},
{
"id": "3",
"word": "ve",
"given_value": "1"
}
]
}
]
Try using on online tool like https://jsonlint.com/ to check your JSON. (if you get errors i recommend build the json again from scratch).
I also recommend checking your json before using it:
if ($arr === null && json_last_error() !== JSON_ERROR_NONE) {
die("incorrect json data");
}
To get your value you have to KNOW how your data looks like and then process it:
foreach($arr as $category) {
foreach($category['data'] as $data) {
if(strstr($data['word'], $word))
echo $category['name'].' '.$data['word'].' '.$data['given_value']."\n";
}
}

Getting all elements on a json schema using php

I really need help on this one.
I have the following Json Schema:
{
"url": "http://www.google.com",
"bodySchema": {
"type": "object",
"properties": {
"SKU": {
"sync": "True",
"mapTo": "SKU",
"type": "string"
},
"WareHouseId": {
"sync": "False",
"mapTo": "",
"type": "integer"
},
"Stock": {
"sync": "True",
"mapTo": "Stock",
"type": "integer"
}
},
"required": {
"0": "SKU",
"1": "Stock"
}
}
}
I would like to retrieve all elements and check if they are required or not,
On the first part (Getting all elements)
What I'm doing is:
foreach ($this->methods as $data) {
if(!empty($data['bodySchema']->properties)){
}
}
But my problem is that I have no way to get the SKU, WarehouseID or Stock, because it's not a key nor anything of the kind.
For my second issue what I was thinking, was to put all required as string and do a loop through them, but if there is any alternative would be glad to know.
You can get the properties out with a simple loop:
foreach ($data->bodySchema->properties as $key => $value) {
// ..
}
If you want to add the required field to the results from above, you can do it like so:
foreach ($data->bodySchema->required as $required) {
$data->bodySchema->properties->$required->required = true;
}
Example with objects or with arrays.

Categories