Skip to content

Commit c5f90a9

Browse files
authored
Merge pull request #19 from TingluoHuang/users/tihuang/decodepayload
decode snappy compressed base64 json.
2 parents d8d6f57 + e63facc commit c5f90a9

File tree

3 files changed

+30
-8
lines changed

3 files changed

+30
-8
lines changed

package-lock.json

+5
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@
1313
"react-codemirror2": "^7.1.0",
1414
"react-copy-to-clipboard": "^5.0.2",
1515
"react-dom": "^16.13.1",
16-
"react-scripts": "3.4.1"
16+
"react-scripts": "3.4.1",
17+
"snappyjs": "^0.6.1"
1718
},
1819
"scripts": {
1920
"start": "react-scripts start",

src/components/JSONFormatter/JSONFormatter.jsx

+23-7
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import React, { Component } from "react";
22
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
33
import { UnControlled as CodeMirror } from 'react-codemirror2'
4+
import SnappyJS from 'snappyjs'
5+
import { Buffer } from "buffer";
46

57
const zlib = require('zlib');
68
require('codemirror/mode/javascript/javascript');
@@ -61,16 +63,30 @@ export class JSONFormatter extends Component {
6163

6264
formatJSON(input) {
6365
if (input) {
66+
var jsonString = "";
6467
if (!input.startsWith("0x")) {
65-
throw new Error("input needs to be a Hex String starts with '0x'.");
68+
input = input.replace(/\r?\n|\r/g, "");
69+
// check whether the input is a base64 string and then try use snappy to decompress it
70+
var base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
71+
if (base64regex.test(input)) {
72+
var uncompressed = SnappyJS.uncompress(Buffer.from(input, 'base64'));
73+
let utf8decoder = new TextDecoder()
74+
jsonString = utf8decoder.decode(uncompressed);
75+
}
76+
else {
77+
throw new Error("input needs to be a Hex String starts with '0x' or valid base64 string.");
78+
}
6679
}
67-
input = input.substring(2);
68-
var hex = Buffer.from(input, 'hex');
69-
if (input.toLowerCase().startsWith("1f8b")) {
70-
// gzip string, need to unzip first
71-
hex = zlib.gunzipSync(hex);
80+
else {
81+
input = input.substring(2);
82+
var hex = Buffer.from(input, 'hex');
83+
if (input.toLowerCase().startsWith("1f8b")) {
84+
// gzip string, need to unzip first
85+
hex = zlib.gunzipSync(hex);
86+
}
87+
jsonString = hex.toString('utf-8');
7288
}
73-
var jsonString = hex.toString('utf-8');
89+
7490
var parsedData = JSON.parse(jsonString);
7591
var outputText = JSON.stringify(parsedData, null, 4);
7692
return outputText;

0 commit comments

Comments
 (0)