Json文件刪除元素


方法1:delete

注意,該方法刪除之后的元素會變為null,並非真正的刪除!!!

舉例:

原json:

{
   "front" : {
      "image" : [
         {
            "file" : "D:\\app\\data\\temp\\gn_image_0.jpg",
            "height" : 253,
            "width" : 190,
            "x" : 49,
            "y" : 110
         },
         {
            "file" : "D:\\app\\data\\temp\\gn_image_1.jpg",
            "height" : 60,
            "width" : 260,
            "x" : 375,
            "y" : 460 } ],
      "text" : [
         {
            "b" : true,
            "data" : "姓名  盧戰士",
            "font" : "宋體",
            "size" : 8,
            "x" : 260,
            "y" : 150
         }
      ]
   }
}

我們現在讀取該JSON文件然后刪除image第一個元素:

var fs=require("fs");
var path=require("path");
var jsonStr=fs.readFileSync(path.join(__dirname,"../1.json"));
var json=JSON.parse(jsonStr);
delete json.front.image[0];
console.log(JSON.stringify(json));

最后打印內容為:

{
    "front": {
        "image": [
            null,
            {
                "file": "D:\\app\\data\\temp\\gn_image_1.jpg",
                "height": 60,
                "width": 260,
                "x": 375,
                "y": 460
            }
        ],
        "text": [
            {
                "b": true,
                "data": "姓名  盧戰士",
                "font": "宋體",
                "size": 8,
                "x": 260,
                "y": 150
            }
        ]
    }
}

方法2:使用數組的方式刪除,徹底刪除

JSON數據是由對象和數組數據結構組成,我們只要學會javascript中對對象和數組的刪除方法即可對JSON項進行刪除操作

 

用splice方法

 

這個方法很強大,可以對數組任意項進行增加,刪除,替換操作

第一個參數是准備操作的數組位置,第二個參數是從操作位置開始后面的要操作的數組項數,第三個以后的就是,被替換后的內容(如果第三個參數為空就是刪除)

 

 

var fs=require("fs");
var path=require("path");
var jsonStr=fs.readFileSync(path.join(__dirname,"../1.json"));
var json=JSON.parse(jsonStr);
 json.front.image.splice(0,1);
console.log(JSON.stringify(json));

 

最終打印結果:

{
    "front": {
        "image": [
            {
                "file": "D:\\app\\data\\temp\\gn_image_1.jpg",
                "height": 60,
                "width": 260,
                "x": 375,
                "y": 460
            }
        ],
        "text": [
            {
                "b": true,
                "data": "姓名  盧戰士",
                "font": "宋體",
                "size": 8,
                "x": 260,
                "y": 150
            }
        ]
    }
}

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM