JavaScript 動態處理 Json

本文中的 JSON 測試資料來源於行政機關辦公(放假)日曆表 API
    
// data from taiwan calendar api
// const url = "https://cdn.jsdelivr.net/gh/ruyut/TaiwanCalendar/data/2023.json";

const inputJsonString =`
    [
        {
            "date": "20230101",
            "week": "日",
            "isHoliday": true,
            "description": "開國紀念日"
        },
        {
            "date": "20230102",
            "week": "一",
            "isHoliday": true,
            "description": "補假"
        },
        {
            "date": "20230103",
            "week": "二",
            "isHoliday": false,
            "description": ""
        }
    ]
        `;
    

將 JSON 字串直接轉換為物件

    
const inputJson = JSON.parse(inputJsonString);
console.log("inputJson", inputJson);
// [{date: "20230101", week: "日", isHoliday: true, description: "開國紀念日"}, {date: "20230102", week: "一", isHoliday: true, description: "補假"}, {date: "20230103", week: "二", isHoliday: false, description: ""}]
    

將物件轉換為 JSON 字串

    
const jsonString = JSON.stringify(inputJson);
console.log("jsonString", jsonString);
// [{"date":"20230101","week":"日","isHoliday":true,"description":"開國紀念日"},{"date":"20230102","week":"一","isHoliday":true,"description":"補假"},{"date":"20230103","week":"二","isHoliday":false,"description":""}]
    

動態取得 JSON 的屬性名稱

因為此示範的 JSON 是 Array,所以我們取第 0 筆資料,用該筆資料來取得所有屬性(假設 Array 內的所有資料都具有同樣的屬性)
    
const json = JSON.parse(inputJsonString);
const keys = Object.keys(json[0]);
console.log("keys:", keys); // console.log("keys:", keys); // ["date", "week", "isHoliday", "description"]
    

動態增加、刪除屬性

上面有提到可以將物件動態轉換為 JSON 字串,反之亦然。所以要動態增加、刪除的方式其實就是操作物件後再輸出為 JSON 字串。
    
const obj = {}; // const obj = new Object();
console.log(obj); // {}
console.log(JSON.stringify(obj)); // {}

// 增加屬性 方法一
obj.name = "ruyut";
console.log(obj); // {name: "ruyut"}
console.log(JSON.stringify(obj)); // {"name":"ruyut"}

// 增加屬性 方法二
obj["age"] = 100;
console.log(obj); // {name: "ruyut", age: 100}
console.log(JSON.stringify(obj)); // {"name":"ruyut","age":100}

// 刪除屬性
delete obj.age;
console.log(obj); // {name: "ruyut"}
console.log(JSON.stringify(obj)); // {"name":"ruyut"}
    



參考資料:

留言