Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming JSON subkeys using PHP

Tags:

json

php

I'm trying to help a JSON structure format from an existing project, and the goal is to rename some subkeys not the value. The JSON format like this

{
  "table-name": "Kiwi",
  "created-on": "November 20, 2021",
  "token": "lsUVozOB2TxhvMv",
  "icons": "default",
  "links": "default",
  "extra": "default",
  "mode": "Private",
  "collaborators": [],
  "columns": {
    "Name": {
      "type": "text",
      "extra": ""
    },
    "Info": {
      "type": "longtext",
      "extra": ""
    },
    "Status": {
      "type": "droplist",
      "extra": {
        "fr": "Pending",
        "sc": "On-going",
        "th": "Completed",
        "fo": "Cancelled"
      }
    }
  },
  "data": [{
      "Name": "Team Reports",
      "Info": "Submitting marketing materials reports",
      "Status": "Completed"
    },
    {
      "Name": "Fabia HR",
      "Info": "Brian asking for a report",
      "Status": "Pending"
    },
    {
      "Name": "Fabia",
      "Info": "Meeting with CEO @cafe 9:00",
      "Status": "Cancelled"
    }
  ]
}

And we're looking into the columns to rename the Name into Task and still keep the other. After using array push and slice the keys, I'm getting 0 as the keys and "Task as subkeys like

"0":{
  "Task":{
    "type":"text",
    "extra":""
  },

The code looks like this. Please do share your solutions in your spare time, thank you in advance, really appreciate any attention. Total noob here 🖐 PHP:

$file = file.json;  
$jsn = file_get_contents($file);
$data = json_decode($jsn, true);
 
//get name data array 
$sub_data = $data['columns']['Name'];

$new_rename = array(
    "Task" => $sub_data;
);

array_push($data['columns'],$new_rename);

//now delete old "Name";
array_slice($data['columns'],'Name')

//save stuff
$jsn = json_encode($data);
file_put_contents($file,$jsn);
like image 228
Maharlikan Avatar asked May 08 '26 23:05

Maharlikan


1 Answers

Given you're working with JSON objects and thus PHP associative arrays (as opposed to numerically indexed), all you really need to do is set the new property and unset the old one

$data["columns"]["Task"] = $data["columns"]["Name"];
unset($data["columns"]["Name"]);

Demo ~ https://3v4l.org/7pBpZ

like image 132
Phil Avatar answered May 11 '26 12:05

Phil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!