$ sudo apt-get install nodejs
安装完毕, 我们可以使用如下命令进行测试:
$ nodejs -v
v0.10.25
第二,准备一个测试json文件, test.json,内容如下:
[javascript] view plain copy
{
"person": {
"name": "wanger",
"birth": "1999"
}
}
第三,创建js脚本来解析json文件,main.js
[javascript] view plain copy
#!/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
解析json数据
var json = { contry:{ area:{ man:"12万", women:"10万" } } }//方式一:使用eval解析
var obj = eval(json)
alert(obj.constructor)
alert(obj.contry.area.women)
//方式二:使用Funtion函数
var strJSON = "{name:'json name'}"//得到的JSON
var obj = new Function("return" + strJSON)()//转换后的JSON对象
alert(obj.name)//json name
alert(obj.constructor)
//复杂一点的json数组数据的解析
var value1 = [{"c01":"1","c02":"2","c03":"3","c04":"4","c05":"5","c06":"6","c07":"7","c08":"8","c09":"9"}, {"c01":"2","c02":"4","c03":"5","c04":"2","c05":"8","c06":"11","c07":"21","c08":"1","c09":"12"}, {"c01":"5","c02":"1","c03":"4","c04":"11","c05":"9","c06":"8","c07":"1","c08":"8","c09":"2"}] var obj1 = eval(value1)
alert(obj1[0].c01)
//复杂一点的json的另一种形式
var value2 = {"list":[ {"password":"1230","username":"coolcooldool"}, {"password":"thisis2","username":"okokok"}], "array":[{"password":"1230","username":"coolcooldool"},{"password":"thisis2","username":"okokok"}]}
var obj2 = eval(value2)
alert(obj2.list[0].password)