|
1 | 1 | import React, { Component } from "react";
|
2 | 2 | import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
|
3 | 3 | import { UnControlled as CodeMirror } from 'react-codemirror2'
|
| 4 | +import SnappyJS from 'snappyjs' |
| 5 | +import { Buffer } from "buffer"; |
4 | 6 |
|
5 | 7 | const zlib = require('zlib');
|
6 | 8 | require('codemirror/mode/javascript/javascript');
|
@@ -61,16 +63,30 @@ export class JSONFormatter extends Component {
|
61 | 63 |
|
62 | 64 | formatJSON(input) {
|
63 | 65 | if (input) {
|
| 66 | + var jsonString = ""; |
64 | 67 | 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 | + } |
66 | 79 | }
|
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'); |
72 | 88 | }
|
73 |
| - var jsonString = hex.toString('utf-8'); |
| 89 | + |
74 | 90 | var parsedData = JSON.parse(jsonString);
|
75 | 91 | var outputText = JSON.stringify(parsedData, null, 4);
|
76 | 92 | return outputText;
|
|
0 commit comments