Nodejs處理Json文件并將處理后的數(shù)據(jù)寫入新文件中
處理Json文件并將處理后的數(shù)據(jù)寫入新文件
問題描述
事情是這樣的,朋友讓我處理一個json文件并將處理后的數(shù)據(jù)寫入新文件。這個json文件的結(jié)構(gòu)如下:
[ ?? ?{ ? ? ? ? "head_img": "http://wx.qlogo.cn/mmhead/xxxxxxxxxxx", ? ? ? ? "nick_name": "xxxxxxx", ? ? ? ? "user_name": "", ? ? ? ? "wxid": "wxid_xxxxxxxxxxxx" ? ? }, ? ? ... ]
這個json文件中的這個json數(shù)組大小是25w條數(shù)據(jù),現(xiàn)在他只想要wxid這個屬性的值,并且將它寫出到一個txt的文件中,沒5000個為一個txt文件,每個值為一行。也就是最后給他50個txt文件,每個里面有5000行wxid的值。
實現(xiàn)過程
解決問題的方法有很多,可以用python、nodejs、Java等任何你熟悉的語言實現(xiàn),我這里使用nodejs來實現(xiàn)一下,因為它簡單并且不需要引入第三方的庫。
這里涉及到了文件的讀取和寫入,因此用到nodejs自帶的fs模塊。具體實現(xiàn)代碼如下:
const fs = require("fs")?? ?//引入fs模塊 const data = fs.readFileSync('test.json','utf8');?? ?//讀取json文件 let temp = JSON.parse(data)?? ?//將數(shù)據(jù)解析為json對象 let tempIndex = 0;?? ?//臨時索引,用來計數(shù)是否到達5000條 let tempFileCount = 1?? ?//臨時文件計數(shù),用于計數(shù)文件名,result1...result50 temp.forEach(element => {?? ?//遍歷json數(shù)組 ? ? if(tempIndex<5000){?? ?//判斷是否小于5000,如果是則寫入當(dāng)前文件,這里使用的是追加的寫入方式 ? ? ? ? fs.appendFileSync("result"+tempFileCount+".txt",element.wxid+'\r','utf8',function(err){},tempIndex++) ? ? ? ?? ? ? }else{?? ?//當(dāng)tempIndex等于5000時寫入新的文件,并且將文件名計數(shù)加一 ? ? ? ? console.log("create new file") ? ? ? ? tempFileCount++; ? ? ? ? fs.appendFileSync("result"+tempFileCount+".txt",element.wxid+'\r','utf8',function(err){},console.log(tempFileCount+': 開始寫入')) ? ? ? ? tempIndex = 0; ? ? } });
用Nodejs解析json數(shù)據(jù)
nodejs是服務(wù)器端的javascript的處理平臺。json(JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式。我們在寫服務(wù)端的程序時往往需要使用json來處理數(shù)據(jù)。
這里我們用一個簡單的例子來演示如何用nodejs來處理json數(shù)據(jù)文件。
第一,我們需要在ubuntu14.04上安裝nodejs,我們可以使用如下命令:
$ sudo apt-get install nodejs
安裝完畢, 我們可以使用如下命令進行測試:
$ nodejs -v v0.10.25
第二,準備一個測試json文件, test.json,內(nèi)容如下:
{ ? "person": { ? ? "name": "wanger", ? ? "birth": "1999" ? } }
第三,創(chuàng)建js腳本來解析json文件,main.js
#!/usr/bin/nodejs var cwd = process.argv[1].substring(0, process.argv[1].lastIndexOf("/")); var fs = require('fs'); ? function load(file, cb) { ? ? ? ? fs.readFile(file, function(err, data) { ? ? ? ? ? ? ? ? if (err) ? ? ? ? ? ? ? ? ? ? ? ? throw err; ? ? ? ? ? ? ? ? cb(JSON.parse(data.toString())); ? ? ? ? }); } ? (function() { ? ? ? ? if (process.argv.length < 2) { ? ? ? ? ? ? ? ? console.log("usage\n\t" + process.argv[1] + " loadfile"); ? ? ? ? ? ? ? ? return; ? ? ? ? } ? ? ? ? load(process.argv[2], function(obj) { ? ? ? ? ? ? ? ? console.log("%s\n", obj.person.name); ? ? ? ? ? ? ? ? console.log("%s\n", obj.person.birth); ? ? ? ? }); })();
第四,測試和運行
$ ./main.js test.json wanger 1999
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Node.js模擬發(fā)起http請求從異步轉(zhuǎn)同步的5種用法
這篇文章主要介紹了Node.js模擬發(fā)起http請求從異步轉(zhuǎn)同步的5種方法,下面總結(jié)了幾個常見的庫 API 從異步轉(zhuǎn)同步的幾種方法。需要的朋友可以參考下2018-09-09Linux CentOS系統(tǒng)下安裝node.js與express的方法
這篇文章主要給大家介紹了在Linux CentOS系統(tǒng)下安裝node.js與express的方法,文中介紹的非常詳細,相信對大家具有一定的參考價值,需要的朋友們下面來一起看看吧。2017-04-04