Can comments be used in JSON?

后端 未结 30 1650
别跟我提以往
别跟我提以往 2020-11-22 02:16

Can I use comments inside a JSON file? If so, how?

30条回答
  •  不思量自难忘°
    2020-11-22 02:45

    This is a "can you" question. And here is a "yes" answer.

    No, you shouldn't use duplicative object members to stuff side channel data into a JSON encoding. (See "The names within an object SHOULD be unique" in the RFC).

    And yes, you could insert comments around the JSON, which you could parse out.

    But if you want a way of inserting and extracting arbitrary side-channel data to a valid JSON, here is an answer. We take advantage of the non-unique representation of data in a JSON encoding. This is allowed* in section two of the RFC under "whitespace is allowed before or after any of the six structural characters".

    *The RFC only states "whitespace is allowed before or after any of the six structural characters", not explicitly mentioning strings, numbers, "false", "true", and "null". This omission is ignored in ALL implementations.


    First, canonicalize your JSON by minifying it:

    $jsonMin = json_encode(json_decode($json));
    

    Then encode your comment in binary:

    $hex = unpack('H*', $comment);
    $commentBinary = base_convert($hex[1], 16, 2);
    

    Then steg your binary:

    $steg = str_replace('0', ' ', $commentBinary);
    $steg = str_replace('1', "\t", $steg);
    

    Here is your output:

    $jsonWithComment = $steg . $jsonMin;
    

提交回复
热议问题