Add to a JSON object, with PHP - 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": ...}}

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?

Getting 2nd level of JSON data in 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>';
}

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.

How do I turn a POSTed JSON value into PHP?

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);

Foreach empty from json

I have the following url:
https://graph.facebook.com/123456/likes?access_token=__ACCESS_TOKEN__&format=json
which I then do:
$likesList = json_decode(file_get_contents("https://graph.facebook.com/123456/likes?access_token=$access_token&format=json"),true);
which produces e.g.
{
"data": [
{
"name": "yo yo yo",
"category": "Entertainer",
"id": "45640987076",
"created_time": "2012-04-18T16:14:09+0000"
},
{
"name": "Tony Smith",
"category": "Musician/band",
"id": "456456456456",
"created_time": "2012-02-22T06:56:18+0000"
},
{
"name": "Stations",
"category": "Company",
"id": "567657567",
"created_time": "2012-01-30T23:08:39+0000"
}
]
}
and I then want to list e.g. all the names returned so:
foreach ($likesList->data as $element2){
$name = $element2[name];
echo $name;
}
But it's empty?
See this visualization of your data structure.
As you are receiving an array, you need $list["data"] and not $list->data. Also don't forget to quote the array key "name".
foreach ($likesList['data'] as $element2){
$name = $element2['name'];
echo $name;
}
After json_decode with parameter true you will have associative array. You can access to value by string key. Like in example above.

Categories