我们有一个应用程序可以生成复杂的JSON对象,其属性和值已转换为十六进制。如何将它们恢复为字符串?
示例对象:
{
"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对象。
答案 0 :(得分:1)
您的解析器函数有效,但它需要处理对象和数组,并以递归方式调用:
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;
}
答案 1 :(得分:1)
您需要进行类型检查和递归。 虽然这段代码没有使用它,但我还建议您使用underscore.js来简化循环和类型检查。
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) );
答案 2 :(得分:0)
您应该将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);