Search code examples
javascriptjsonnode.jsstring-conversion

Parse Hexed JSON Object


We have an app that generates complex JSON objects whose properties and values have been converted to hexadecimals. How can I revert them them to strings?

Sample Object:

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

Code so far:

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 );

But this code only works on simple JSON objects with simple key-value pairs.


Solution

  • You need to do type check and recursion. Although this code did not use it, I also suggest you to use underscore.js to simplify looping and type checking.

    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) );