1. 程式人生 > 其它 >1.3 nodejs對json檔案解析

1.3 nodejs對json檔案解析

技術標籤:Nodejsnodejs處理json檔案nodejs解析jsonnodejs遍歷jsonnodejs提取json

一、json檔案v6.json

{
	"total": 8310,
	"definitions": {
		"test0001": {
			"key": "test0001",
			"sort": 27,
			"count": 71
		},
		"test0002": {
			"key": "test0002",
			"sort": 28,
			"count": 34
		},
		"test0003": {
			"key": "test0003",
			"sort": 9976,
			"count": 30
		},
		"test0004": {
			"key": "test0004",
			"sort": 9999,
			"count": 2
		},
		"test0005": {
			"key": "test0005",
			"sort": 2417805,
			"count": 5
		},
		"test0006": {
			"key": "test0006",
			"sort": 9999,
			"count": 7
		}
	}
}

解析

const  fs = require('fs');

var v6 = fs.readFileSync("v6.json");
var v6Json = JSON.parse(v6);
var v6Set= new Set();

for(let name in v6Json['definitions']){
   let  temp ={
        key:v6Json['definitions'][name].key,
        sort:v6Json['definitions'][name].sort,
        count:v6Json['definitions'][name].count,
    }
    v6Set.add(temp);
}

二、json檔案v5.json

{
	"code": "000000",
	"msg": "成功",
	"data": [{
			"typeKey": "test010",
			"count": "72",
			"sort": "9999"
		},
		{
			"typeKey": "test008",
			"count": "1",
			"sort": "9999"
		},
		{
			"typeKey": "test006",
			"count": "1806",
			"sort": "9999"
		},
		{
			"typeKey": "test004",
			"count": "23",
			"sort": "9999"
		},
		{
			"typeKey": "test003",
			"count": "1",
			"sort": "9999"
		},
		{
			"typeKey": "test001",
			"count": "9",
			"sort": "9999"
		},

		{
			"typeKey": "test005",
			"count": "3",
			"sort": "2419405"
		}
	]
}

解析

var v5 = fs.readFileSync("v5.json");
var v5Json =JSON.parse(v5);
var v5Set = new Set();
for(let name in v5Json['data']){
    let  temp ={
        key:v5Json['data'][name].typeKey,
        sort:v5Json['data'][name].sort,
        count:v5Json['data'][name].count,
    }
    v5Set.add(temp);
}
   
  

三、輸出結果如下