How is binary data handled in json?

Viewed 1653

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 Answers

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]
}
Related