parsingJed对象

我们有一个应用程序生成复杂的JSON对象,其属性和值已被转换为hex。 我怎样才能把它们还原成string?

示例对象:

{ "636f756e747279": { "6e616d65": "43616e616461", "636f6465": "4341" }, "617574686f72": { "6e616d65": "4a61736d696e652048656174686572", "67656e646572": "66", "626f6f6b496473": [ "6a65683233696f", "33393233393130" ] } } 

目前代码:

 var data = require( './data.json' ); var parsed = {}; Object.keys( data ).forEach( function( key, index, keys ) { var prop = new Buffer( key, 'hex' ).toString(); var value = new Buffer( data[ key ], 'hex' ).toString(); parsed[ prop ] = value; }); console.log( parsed ); 

但是这个代码只能用简单的键值对在简单的JSON对象上工作。

你需要做types检查和recursion。 尽pipe这段代码并没有使用它,但我也build议你使用underscore.js来简化循环和types检查。

 var data = { "636f756e747279": { "6e616d65": "43616e616461", "636f6465": "4341" }, "617574686f72": { "6e616d65": "4a61736d696e652048656174686572", "67656e646572": "66", "626f6f6b496473": [ "6a65683233696f", "33393233393130" ] } }; var unpack = function(hex) { return new Buffer( hex, 'hex' ).toString(); }; var convert_object = function(data) { if (typeof data === 'string') { return unpack(data); } else if (Array.isArray( data )) { return data.map(convert_object); } else if (typeof data === 'object') { var parsed = {}; Object.keys( data ).forEach( function( key, index, keys ) { parsed[ unpack(key) ] = convert_object( data[key]); }); return parsed; } else { throw ("Oops! we don't support type: " + (typeof data)); } }; console.log( convert_object(data) ); 

你的parsing器函数是有效的,但它需要处理对象和数组,并recursion调用:

 function parse(obj) { var parsedObj = {}; // If it's a string, just de-hexify it if (typeof(obj) == 'string') { return new Buffer( obj, 'hex' ).toString(); } // Otherwise, parse each key / value Object.keys( obj ).forEach( function( key ) { // Translate the key var prop = new Buffer( key, 'hex' ).toString(); // Get the value var value = obj[key]; // If value is an array, recursively parse each value if (Array.isArray(value)) { parsedObj[prop] = value.map(parse); } // Otherwise recursively parse the value, which is an object or array else { parsedObj[prop] = parse(value); } }); // Return the result return parsedObj; } 

您应该将reviver参数用于JSON.parse函数:

 var file = require('fs').readFileSync('./data.json', 'utf8'); function unpack(hex) { return new Buffer( hex, 'hex' ).toString(); } var data = JSON.parse(file, function(k, v) { if (k == "" || Array.isArray(this)) return v; if (typeof v == "string") v = unpack(v); this[unpack(k)] = v; }); console.log(data);