How to add data to a JSON file - php

I would like to be able to add to a JSON file via a online portal using PHP.
I have attempted to do this with the code below, How ever I am not familiar with PHP so I can not get further.
<?php
//Get the data from the url
$name = $_GET['name'];
$email = $_GET['email'];
// read json file
$data = file_get_contents('example.json');
// decode json
$json_arr = json_decode($data, true);
// add data
$json_arr[] = array(4, 'Name'=>$name, 'email'=>$email);
// encode json and save to file
file_put_contents('example.json', json_encode($json_arr));
?>
My attempt:
[{"0":4,"Name":"kieran","email":"ex#ex.com"}]
What I would want to add
//This is want the JSON should be
"0": {
"conditionName": "u",
"ignoreFollowing": false,
"emailsThisSession": 0,
"recieverEmails": [
"example#g.c"
],
"alertType": 1,
"emailProperty": 2,
"triggers": {
"0": {
"Property": 2,
"Value": "zk-reg",
"ComparisonType": "Equals"
}
}
},
This is the whole JSON:
{
"0": {
"conditionName": "u",
"ignoreFollowing": false,
"emailsThisSession": 0,
"recieverEmails": [
"example#g.c"
],
"alertType": 1,
"emailProperty": 2,
"triggers": {
"0": {
"Property": 2,
"Value": "zk-reg",
"ComparisonType": "Equals"
}
}
},
"1": {
"conditionName": "k",
"ignoreFollowing": false,
"emailsThisSession": 0,
"recieverEmails": [
"h#f.com"
],
"alertType": 1,
"emailProperty": 0,
"triggers": {
"0": {
"Property": 0,
"Value": "",
"ComparisonType": "Equals"
}
}
}
}

If I am understanding you correctly you want to do something like
<?php
// read json file in this case I just include it in the script for simplicity
$data = '{
"0": {
"conditionName": "u",
"ignoreFollowing": false,
"emailsThisSession": 0,
"recieverEmails": [
"example#g.c"
],
"alertType": 1,
"emailProperty": 2,
"triggers": {
"0": {
"Property": 2,
"Value": "zk-reg",
"ComparisonType": "Equals"
}
}
},
"1": {
"conditionName": "k",
"ignoreFollowing": false,
"emailsThisSession": 0,
"recieverEmails": [
"h#f.com"
],
"alertType": 1,
"emailProperty": 0,
"triggers": {
"0": {
"Property": 0,
"Value": "",
"ComparisonType": "Equals"
}
}
}
}';
// decode json
$json_arr = json_decode($data, true);
echo "Before Count " . count($json_arr);
// add data
//put the array of variables you want to add into its own var, add each variable you want, I've done the first two
$rowToAdd = array("conditionName" => "y", "ignoreFollowing" => false, "emailsThisSession" => 800, "recieverEmails" => array("h#f.com"));
//use array_push to add to the current array rather over-writing it
array_push($json_arr , $rowToAdd);
echo "After Count " . count($json_arr);
// encode json and save to file
file_put_contents('example.json', json_encode($json_arr));
?>

Try it:
//$data is data you wanto add.
$json_files = file_get_contents('example.json');
$tempArray = json_decode($json_files);
array_push($tempArray, $data);
$jsonData = json_encode($tempArray);
file_put_contents('example.json', $jsonData);

Related

How to take a JSON content and return it in a wordpress function (php)?

I have a wordpress endpoint and I have some json data.
Unfortunately I dont know how to return this json data in the function. I tried json_decode but it doesn't return anything. Then endpoint works. If I use json_encode it returns data, but also include linebreaks and stuff. The problem seems to be with the syntax as it is already a complete json what I have. How can I return something that is already in json syntax?
add_action('wp_ajax_nopriv_inboundCall', 'testFunction');
add_action('wp_ajax_inboundCall', 'testFunction');
function testFunction() {
echo json_decode('{
"testData": [
{
"_id": "1",
"name": "testName1"
},
{
"_id": "2",
"name": "testName2"
},
],
"testState": {
"1": [
1,
0
"2": [
1,
0
]
}
}');
die();
}
function testFunction() {
return json_decode('{
"testData": [
{
"_id": "1",
"name": "testName1"
},
{
"_id": "2",
"name": "testName2"
},
],
"testState": {
"1": [
1,
0
"2": [
1,
0
]
}
}'); }
I saved the output of json_decode to a variable and then run json_encode on that variable. Now it seems to work.
function inboundCall() {
$json = json_decode('{
"topics": [
{
"_id": "1",
"name": "davisio",
"crdate": "2022-01-17T12:40:03.430Z",
"modified": "2022-01-17T12:40:03.430Z"
},
{
"_id": "2",
"name": "LoRaWAN",
"crdate": "2022-01-17T12:40:33.848Z",
"modified": "2022-01-17T12:40:33.848Z"
},
{
"_id": "3",
"name": "Kommunale Beziehungen",
"crdate": "2022-01-19T15:17:10.094Z",
"modified": "2022-01-19T15:17:10.094Z"
},
{
"_id": "4",
"name": "Test",
"crdate": "2022-03-31T13:29:41.799Z",
"modified": "2022-03-31T13:29:41.799Z"
}
],
"serviceState": {
"1": [
1,
0,
0,
1,
0,
0,
0,
1
],
"2": [
1,
0,
0,
0,
0,
0,
0,
1
],
"4": [
1,
0,
0,
0,
0,
0,
0,
1
]
}
}');
echo json_encode($json);
die();
}

How to get particular data from json url

I have following Json Data in php url
File name : house.php
{
"Error": "",
"ErrorCode": 0,
"Guid": "",
"Id": 0,
"Success": true,
"Value": [
{
"MAIN": 225,
"PHASE": 219418523,
"G": "7TH Division",
"GI": "2031892",
"DOOR": "8907",
"Gate": {
"RG": 2,
"BNS": "4 Window",
"BS": {
"SB1": 2
},
"TQ": [
{
"Key": 1,
"Value": {
"T1": 2
}
},
{
"Key": 2,
"Value": {}
}
],
"MR": -1,
"MS": 600
},
"AA": "81",
"AI": "8745524"
},
{
"MAIN": 300,
"PHASE": 219418523,
"G": "8TH Division",
"GI": "4526892",
"DOOR": "8877",
"GATE": {
"RG": 2,
"BNS": "5 Window",
"BS": {
"SB1": 2
},
"TQ": [
{
"Key": 1,
"Value": {
"T1": 2
}
},
{
"Key": 2,
"Value": {}
}
],
"MR": -1,
"MS": 600
},
"AA": "91",
"AI": "8758421"
}]}
I need particular data "G", "G1", "DOOR", "AA", A1" alone to display in my new php file :
completehouse.php in json format what code to give to get particular data.
<?php
$url="house.php";
$text = file_get_contents($url);
header('Content-Type: application/json');
echo $text;
?>
Currently i am using https://codebeautify.org/online-json-editor manually each time by using transform data
query : [*].{G: G, G1: G1, DOOR: DOOR, AA: AA, AI: AI} and getting output
{
"Error": "",
"ErrorCode": 0,
"Guid": "",
"Id": 0,
"Success": true,
"Value": [
{
"G": "7TH DIVISION",
"G1": "2031892",
"DOOR": "8907",
"AA": "81",
"AI": "8745524"
},
{
"G": "8TH DIVISION",
"G1": "4526892",
"DOOR": "8877",
"AA": "85",
"AI": "8759544"
}
]
}
Please someone help me to fix my manual work and save my time.
You can decode your json and then get the exact value of what you want.
$json = '....';
$parsed = json_decode($json,true);
$result = [];
if($parsed['Success']){ // check if your api json response is true.
foreach($parsed['Value'] as $val){
if($val['AI']> = 9000000){
$result[] = [
"G"=> $val['G'],
"GI"=> $val['GI'],
"DOOR"=> $val['DOOR'],
"AA"=> $val['AA'],
"AI"=> $val['AI']
];
}
// or what you want.
}
}
echo json_encode($result);
see demo
As you only need to manipulate the Value column so below code will keep all values same but get the specific columns from Value.
$url="house.php";
$text = file_get_contents($url);
$data = json_decode($text, true);
if ($data['Success'] === true) {
$v = [];
$columns = ["G", "GI", "DOOR", "AA", "AI"];
for ($i = 0; $i< count($data['Value']); $i++) {
foreach ($data['Value'][$i] as $key => $val) {
if (in_array($key, $columns)) {
$v[$key] = $val;
}
}
$data['Value'][$i] = $v;
}
}
$text = json_encode($data);

i want php api responce in one array list

$MobileNo = $_POST['MobileNo'];
$query = "SELECT * FROM tblLotProcessStatus WHERE MobileNo = $MobileNo" ;
$result = sqlsrv_query($pdo,$query);
while ($row = sqlsrv_fetch_array($result,(SQLSRV_FETCH_ASSOC)))
{
if($row)
{
$status=array();
array_push($status,$row);
$response["status"] = $status;
$response["responce_code"] = 200;
$response["error_code"] = 0;
$response["error_msg"] = "status avialable";
echo json_encode($response);
}
JSON output:
{
"error": false,
"status": [
{
"id": 1,
"strPartyCode": "00000000",
"intLotID": "257949",
"MobileNo": "9879105144 ",
"Messages": "Lot No : 15023 on Loop Ager/Poly started.,Style:PIGMENT PRINT",
"status": 0,
"Type": "PF ",
"dtmDateTime": {
"date": "2016-02-22 12:00:00.000000",
"timezone_type": 3,
"timezone": "Europe/Berlin"
},
"strLotNo": "N 15023",
"strProcess": "Loop Ager/Poly,Style:PIGMENT PRINT",
"strStatus": " started."
}
],
"responce_code": 200,
"error_code": 0,
"error_msg": "status avialable"
}{
"error": false,
"status": [
{
"id": 2,
"strPartyCode": "00000000",
"intLotID": "246654",
"MobileNo": "9879105144 ",
"Messages": "Lot No : 8191 on Compacting complited.,Style:DYED",
"status": 0,
"Type": "PF ",
"dtmDateTime": {
"date": "2015-03-09 15:00:00.000000",
"timezone_type": 3,
"timezone": "Europe/Berlin"
},
"strLotNo": "N 8191",
"strProcess": "Compacting,Style:DYED",
"strStatus": " complited."
}
],
"responce_code": 200,
"error_code": 0,
"error_msg": "status avialable"
}
I think the problem is that you are adding all of the details to a new array and then outputing the json_encode()ed data each time. Instead you need to build up 1 array of data and encode it after loading all of the rows from the database...
$response = ["responce_code" => 200, "error_code" => 0,
"error_msg" => "status avialable" ];
while ($row = sqlsrv_fetch_array($result,(SQLSRV_FETCH_ASSOC)))
{
$response["status"][] = $row;
}
echo json_encode($response);
Just an aside - there may be a few spelling mistakes (assuming English spelling) in some of the data, perhaps
$response = ["response_code" => 200, "error_code" => 0,
"error_msg" => "status available" ];

Datatable Invalid JSON response error when my JSON is valid? PHP

My data table that is loading its body from another file with ajax is giving me the invalid JSON error, but when I check my developer tools under network responses my JSON is valid?
This is my PHP and SQL:
<?php
header('Content-Type: application/json');
$output = array('data' => array());
$query = "SELECT * FROM table";
$stmt = sqlsrv_query($sapconn2, $query);
$x = 1;
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){
$output['data'][] = array(
'col_1' => $x,
'ID' => $row['ID'],
'QuoteID' => $row['QuoteID'],
'CardCode' => $row['CardCode'],
'SlpCode' => $row['SlpCode'],
'SlpName' => $row['SlpName'],
'BandA' => $row['BandA'],
'NewPrice' => $row['NewPrice']
);
$x ++;
}
echo json_encode($output);
?>
This is my JSON thats returned in the browser:
{
"data": [
[1, 138, 25, "000123", "222", "test data", 222, 222],
[2, 144, 25, "000123", "132", "test data", 465, 789],
[3, 160, 25, "000123", "456132", "test data", 5599, 5499],
[4, 171, 25, "000123", "789", "test data", 7897, 989],
[5, 172, 25, "000123", "11111", "test data", 1, 11],
[6, 182, 25, "000123", "132166", "test data", 1323, 133],
[7, 183, 25, "000123", "135456", "test data", 1332132, 13213],
[8, 184, 25, "000123", "1321", "test data", 5643214, 6513]
]
}
EDIT:
var testTable = $("#testTable").DataTable({
processing: false,
serverSide: true,
dataType : 'json',
ajax: "test.php",
columns: [
{ "data": "col_1" },
{ "data": "ID" },
{ "data": "QuoteID" },
{ "data": "CardCode" },
{ "data": "SlpCode" },
{ "data": "SlpName" },
{ "data": "BandA" },
{ "data": "NewPrice" }
]
});
This is what datatable waits for:
{
"data": [
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
},
...
]
}
The "data" element is an array of objects, instead you pass an array of array.
You need something like that:
{
"data": [
{ "id": 1, "second_field": 138, "third_field": 25, "fourth_field": "000123", ... },
{ "id": 2, "second_field": 138, "third_field": 25, "fourth_field": "000123", ... },
]
}
EDITED:
$output['data'][] = array(
'col_1' => $x,
'col_2' => $row['ID'],
'col_3' => $row['QuoteID'],
'col_4' => $row['CardCode'],
'col_5' => $row['SlpCode'],
'col_6' => $row['SlpName'],
'col_7' => $row['BandA'],
'col_8' => $row['NewPrice']
);
When you make a request to a server-side script from DataTables with processing set to true then it sends this data.
When it returns data DataTables expects the data to follow these conventions.
You can either take these into account with your server-side script (there's a good example here.) or choose a different method for adding your data. If you perhaps set processing to false you might find everything just works as you expect.
Hope that helps.

Recursively sorting a JSON array

I've looked a little and found an answer that partially does what I am interested in doing, see: Sorting a JSON array in PHP
I have some decoded JSON that looks like this, just a sample.
{
"status": "OK",
"page": {
"rows": 5000,
"more": 0,
"number": 1
},
"accounts": [
{
"connected": 0,
"settings": {
"link_first_study_only": "0",
"update_study_source_on_notify": "1",
"link_external_whitelist": "",
"other_ingress_tags": ""
},
"must_approve_upload": 0,
"css": null,
"share_via_gateway": 0,
"password_expire": 90,
"vanity": "medpics"
}
]
}
What I would like to do is sort everything alphabetically so that it is easier to read and uniform. So that what I would see is:
{
"accounts": [
{
"css": null,
"connected": 0,
"must_approve_upload": 0,
"password_expire": 90,
"settings": {
"link_external_whitelist": "",
"link_first_study_only": "0",
"other_ingress_tags": "",
"update_study_source_on_notify": "1"
},
"share_via_gateway": 0,
"vanity": "medpics"
}
],
"page": {
"more": 0,
"number": 1,
"rows": 5000,
}
"status": "OK"
}
Every element is sorted alphabetically. Is that possible ?
Pretty straightforward
$json = <<<JSON
{
"status": "OK",
"page": {
"rows": 5000,
"more": 0,
"number": 1
},
"accounts": [
{
"connected": 0,
"settings": {
"link_first_study_only": "0",
"update_study_source_on_notify": "1",
"link_external_whitelist": "",
"other_ingress_tags": ""
},
"must_approve_upload": 0,
"css": null,
"share_via_gateway": 0,
"password_expire": 90,
"vanity": "medpics"
}
]
}
JSON;
$json = json_decode($json, true);
function ksort_recursive(&$array) {
ksort($array);
foreach ($array as &$value) {
if (is_array($value)) {
ksort_recursive($value);
}
}
}
ksort_recursive($json);
print_r($json);
Proof of solution here
https://3v4l.org/qUAA0

Categories