简体   繁体   中英

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. 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? 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.

Lets do this.

setup is object I used for testing

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;
}

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