Friday 19 May 2017

Parse data from uint8array to string to json

Anyone know how to correctly parse from a Uint8Array (which essentially just inherits from Buffer..) to a valid json object? Using Node.js as the back-end. I'm uploading a file, and the endpoint receives it as a Uint8Array. Really this is just a .json file. So if you take the Array and to .toString(), it spits out content like so:

bytes.toString()
""someObject": {
    "foo": "bar",
    "baz": {
        "qux": "quux"
    }
}
"

Now, when I attempt to run this through JSON.parse, it fails due to invalid characters. So I can easily see those with the following:

JSON.stringify(bytes.toString())
""\"someObject\": {\r\n\t\"foo\": \"bar\",\r\n\t\"baz\": {\r\n\t\t\"qux\": \"quux\"\r\n\t}\r\n}\r\n""

So I have to remove all these tabs and spaces and newlines in order to parse this into an object. So I do that with the following:

JSON.stringify(bytes.toString().replace(/\r/g, '').replace(/\t/g, '').replace(/\n/g, ''))
""\"someObject\": {\"foo\": \"bar\",\"baz\": {\"qux\": \"quux\"}}""

Great! All that extra garbage in there is removed. So now I can parse this thing. But wait! It only parses it right back into a string:

JSON.parse(JSON.stringify(bytes.toString().replace(/\r/g, '').replace(/\t/g, '').replace(/\n/g, '')))
""someObject": {"foo": "bar","baz": {"qux": "quux"}}"

It's because of the beginning and ending quotes. So... I suppose I could simply go remove those quotes....

But is there just an easier way to do this? Seems so hacky to be doing all this replacing and stringifying back to parsing. What is it that I'm missing here?

All I'm looking for is an actual object to work with in the following format:

{
    "someObject": {
        "foo": "bar",
        "baz": {
            "qux": "quux"
        }
    }
}

I know there is something easy here I'm missing. Please help dumb programmer from smashing face into keyboard! :)



via dvsoukup

No comments:

Post a Comment