Shawn
Shawn

Reputation: 911

Saving javascript objects as strings

This is for a gaming application. In my game I want to save special effects on a player in a single field of my database. I know I could just put a refrence Id and do another table and I haven't taken that option off the table. Edit: (added information) This is for my server in node not the browser.

The way I was thinking about storing the data is as a javascript object as follows:

effects={
           shieldSpell:0,
           breatheWater:0,
           featherFall:0,
           nightVision:0,
           poisonResistance:0,
           stunResistance:0,
           deathResistance:0,
           fearResistance:0,
           blindResistance:0,
           lightningResistance:0,
           fireResistance:0,
           iceResistance:0,
           windResistance:0}

It seems easy to store it as a string and use it using effects=eval(effectsString) Is there an easy way to make it a string or do I have to do it like:

effectsString=..."nightVision:"+effects.nightVision.toString+",poisonResistance:"+...

Upvotes: 0

Views: 1297

Answers (4)

Ruan Mendes
Ruan Mendes

Reputation: 92274

Use JSON.stringify

That converts a JS object into JSON. You can then easily deserialize it with JSON.parse. Do not use the eval method since that is inviting cross-site scripting

//Make a JSON string out of a JS object
var serializedEffects = JSON.stringify(effects);
//Make a JS object from a JSON string
var deserialized = JSON.parse(serializedEffects);

Upvotes: 2

Shawn
Shawn

Reputation: 911

Here was what I've come up with so far just wonering what the downside of this solution is.

        effectsString="effects={"
        for (i in effects){
           effectsString=effectsString+i+":"+effects[i]+","
        }
        effectsString=effectsString.slice(0,effectsString.length-1);
        effectsString=effectsString+"}"

Then to make the object just

eval(effectsString)

Upvotes: 0

Will Stern
Will Stern

Reputation: 17579

JSON parse and stringify is what I use for this type of storatge

var storeValue = JSON.stringify(effects); //stringify your value for storage
// "{"shieldSpell":0,"breatheWater":0,"featherFall":0,"nightVision":0,"poisonResistance":0,"stunResistance":0,"deathResistance":0,"fearResistance":0,"blindResistance":0,"lightningResistance":0,"fireResistance":0,"iceResistance":0,"windResistance":0}"
var effects = JSON.parse(storeValue);  //parse back from your string

Upvotes: 0

Amberlamps
Amberlamps

Reputation: 40448

Serialize like that:

JSON.stringify(effects);

Deserialize like that:

JSON.parse(effects);

Upvotes: 7

Related Questions