weixin_33709219 2014-08-31 11:12 采纳率: 0%
浏览 355

JSON和二进制数据-编码

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 i.e. a key and a value. For example: http://www.w3schools.com/json/. Here there is an Employees list, where each employee has two keys i.e. first name and last name and two values i.e. 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.

  • 写回答

1条回答 默认 最新

  • YaoRaoLov 2014-08-31 14:49
    关注

    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
    
    评论

报告相同问题?