Best way to store JSON in an HTML attribute?

后端 未结 9 1535
梦毁少年i
梦毁少年i 2020-11-30 19:57

I need to put a JSON object into an attribute on an HTML element.

  1. The HTML does not have to validate.

    Answered by Quenti

9条回答
  •  执念已碎
    2020-11-30 20:17

    For simple JSON objects, the code below would work.

    Encode:

    var jsonObject = { numCells: 5, cellWidth: 1242 };
    var attributeString = escape(JSON.stringify(jsonObject));
    

    Decode:

    var jsonString = unescape(attributeString);
    var jsonObject = JSON.parse(jsonString);
    

提交回复
热议问题