2

How can I put binary data in a json string?

The binary data can't be encoded in a base64 string or something like that. Basically I need to know how to put a raw byte array as-is inside a json string.

1 Answer 1

1

The JSON format natively doesn't support binary data. You have to encode it in some ways to convert binary data into text strings that can be accepted as a JSON string.

The most common way of doing so is Base64 encoding

{
    "this_is_base_64": "aGVsbG8hIHVuZGVydGhldm9pZCEgSGVyZSBjYW4gYmUgc29tZSBCaW5hcnkgRGF0YSE="
}

Or alternatively, you can store individual bytes as a number array if the data you're willing to encode is not terribly large.

{
    "my_data": [127, 21, 62, 31, 0, 16, 71, 23, 44, 51, 14, 61, 41, 65]
}
Sign up to request clarification or add additional context in comments.

7 Comments

You can try putting binary data between two double quotes in a JSON text. But I doubt it would be any useful since most parser won't be able to parse it.
Another common way of encoding it is as a hex string -- a string of (an even number of) hex digits.
@underthevoid It shouldn't have. Which base64 library/method are you using to encode the data? Some library might try to be smart and handle charset/CRLF for you, which ruins binary data. However base64 is perfectly capable of encoding and decoding binary data with the right setting for your base64 library (or method).
@underthevoid In fact, a lot of RESTful apis encodes files and images into base64 for transmission within http, then decodes it at the other end to get back the original file or image,
@underthevoid Yes. You can. That's one major use case of base64 :-) The format itself doesn't change anything about the original data. But beware how you encode it though. If you're using C/C++ and uses a encode method that takes only a const char *, but no length, as input, than that's most likely not gonna work. Since it likely assumed a zero-terminated string and not binary data. Your binary data can get chopped off in this case but still, it's not the fault of base64.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.