简体   繁体   English

将JSON对象转换为数字字符串,反之亦然

[英]Transform JSON Object into numerical String and vice versa

(Apologies if a similar question has been asked, I could not find it) (很抱歉,如果有人提出类似问题,我找不到)

Basically I have a JSON object with around 10 properties (fixed amount) that contains personal settings for an app without a user system and I would like users to be able to obtain a code that converts to that object with the proper values for each property. 基本上,我有一个带有大约10个属性(固定数量)的JSON对象,其中包含不带用户系统的应用程序的个人设置,我希望用户能够获得将每个属性具有正确值的代码转换为该对象的代码。 That way, they would be able to access the app with their settings using a permalink. 这样,他们将能够使用固定链接使用其设置访问应用程序。

Question is: Is there a method or a specific indicated technique to transform JSON serialized objects (ie JSON string) into numbers, or an hexadecimal code? 问题是:是否存在将JSON序列化对象(即JSON字符串)转换为数字或十六进制代码的方法或特定指示技术? I've seen several websites do a similar thing from a user point of view. 从用户的角度来看,我已经看到几个网站做类似的事情。

My approach since I have a finite set of properties and possible values would be to hardcode the string (eg if property 1 has value x, first char in string is 1, if it has value y, then it's 2, etc...) but I'm wondering if there is anything best suited for that kind of thing. 我的方法是因为我有一组有限的属性,可能的值是对字符串进行硬编码(例如,如果属性1的值为x,则字符串中的第一个char为1,如果值为y,则为2,依此类推...)但我想知道是否有最适合这种事情的东西。

Lets do this. 我们开工吧。

setup is object I used for testing setup是我用于测试的对象

var setup = { "abc" : "asdasd",
              "special" : "my wife hates me",
              "Kids" : 7564
};

function to generate link: 函数生成链接:

function generateLinkWithSpecialSetup(setup) {
    var str = JSON.stringify(setup);
    var hash = "";
    for(var i =0; i<str.length;i++) {
        hash += str.charCodeAt(i).toString(16);
    }
    return "example.com/special-setup/#" + hash;
}

functions to find setup from hash: 从哈希中查找设置的函数:

function findSetupFromHash() {
    var hash = window.location.hash.substring(1);
    var str = hex2a(hash);
    return JSON.parse(str);
}

function hex2a(hexx) {
    var hex = hexx.toString(); //force conversion
    var str = '';
    for (var i = 0; i < hex.length; i += 2)
        str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
    return str;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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