简体   繁体   中英

JSON and binary data - encoding

I am relatively new to JSON. I have recently added JQuery and JavaScript to an application to make it more interactive and quicker. I understand how JSON works for basic types like: Strings, Numbers etc where there is a MAP ie a key and a value. For example: http://www.w3schools.com/json/ . Here there is an Employees list, where each employee has two keys ie first name and last name and two values ie first name value and last name value.

However, I do not understand how binary data fits into the equation. Say I was to add a new property to the Employee object called: Video, which is a type: application/octet-stream like in the question: Binary Data in JSON String. Something better than Base64 and the value was:

TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz
    IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg
    dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu
    dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo
    ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=

How is this data represented as a MAP? I realise this is probably a simple question, however I do have a JSON book but it does not go into that much detail. I have not found an answer on the web either.

I think you are giving "maps" (KV pairs) too much value. As you've pointed out, JSON has a small number of types: numbers, strings, true and false , null , arrays, and objects. You can think of objects and "maps" as being the same thing. Objects can be built up of the other types, for example:

{
    "person": {
        "name": "John"
    }
}

Person is an object that has a name property that is a string.

So, if you want to represent binary data in JSON, you will have to use one of the existing types (usually as a string via Base64). In the example given in the linked question , the value property of the object is the Base64-encoded value of the file.

{
    "mimetype" : "application/octet-stream”,
    "metadata" : [ ],
    "value" :   "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=",
}

If you are familiar with JavaScript, the following would give you the Base64-encoded value as a string:

var obj = JSON.parse(json);
var value = obj.value; // This is a string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM