Json(/hash) to ruby object? - javascript

In Javascript you can access json as objects.
person = {
name: {
first: "Peter",
last: "Parker"
}
}
person.name.first
In ruby I have to use it like this:
person[:name][:first]
Is it possible to access json (and hash) as an object just like in javascript?

You should check out the Hashie gem. It lets you do just what you are looking for. It has a Mash class which takes JSON and XML parsed hashes and gives you object-like access. It actually does deep-dives into the hash, converting any arrays or hashes inside the hash, etc.
http://github.com/intridea/hashie

There is a json gem in ruby. Perhaps that will help.
http://flori.github.com/json/

JavaScript uses object attributes as its implementation of associative arrays. So, using Ruby's hash type is basically doing the same thing.

Rails has built in support for encoding hashes as JSON and decoding JSON into a hash through ActiveSupport::JSON. Using built-in support avoids the need for installing a gem.
For example:
hash = ActiveSupport::JSON.decode("{ \"color\" : \"green\" }")
=> {"color"=>"green"}
hash["color"]
=> "green"
For more info, see:
http://www.simonecarletti.com/blog/2010/04/inside-ruby-on-rails-serializing-ruby-objects-with-json/

Related

What is the right way to store JavaScript source code in a json object?

I want to edit JavaScript in a textarea and store it back into a JavaScript object. For example I have this object:
var item1 = {
'id' : 1,
'title':'title',
'sourcecode' : "alert('hallo')"
};
If I would change the content to alert("hallo") or a even more complex example does this break my object?
I would think there is some escape function like this https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/escape. But it is marked as deprecated.
So if this is deprecated what would be the right way for storing complex JavaScript code into a JavaScript object?
Should I use stringify ?
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
The JSON.stringify() method converts a JavaScript value to a JSON
string, optionally replacing values if a replacer function is
specified, or optionally including only the specified properties if a
replacer array is specified.
This does not read like there is an automated escape build in.
If you need to send the data to a server, I'd say you should encodeURI your sourceCode, and then JSON.stringify the entire object. When retreiving data from the server, you should decodeURI the sourceCode

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:"+...
Serialize like that:
JSON.stringify(effects);
Deserialize like that:
JSON.parse(effects);
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);
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
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)

how do parse JSON in javascript?

This is my json string
"[{"/stab/cg/{4CD742B1-C1CA-4708-BE78-0FCA2EB01A86}/TOPS_00":[{"key":"C0.A8.01.06","value":"31"},{"key":"C0.A8.50.01","value":"25"},{"key":"C0.A8.50.81","value":"22"},{"key":"E0.00.00.FC","value":"19"},{"key":"C0.A8.01.FF","value":"18"},{"key":"C0.A8.50.FF","value":"18"},{"key":"4A.7D.EC.5F","value":"11"},{"key":"4A.7D.EC.4E","value":"11"},{"key":"SYS:GROUP_TOTALS","value":"158"}]}]"
after eval('('+ evt.data + ')'), i need to get like this
["/stab/cg/{4CD742B1-C1CA-4708-BE78-0FCA2EB01A86}/TOPS_00",[{"key":"C0.A8.01.06","value":"31"},{"key":"C0.A8.50.01","value":"25"},{"key":"C0.A8.50.81","value":"22"},{"key":"E0.00.00.FC","value":"19"},{"key":"C0.A8.01.FF","value":"18"},{"key":"C0.A8.50.FF","value":"18"},{"key":"4A.7D.EC.5F","value":"11"},{"key":"4A.7D.EC.4E","value":"11"},{"key":"SYS:GROUP_TOTALS","value":"158"}]]
How can i get this using javascript?
If you can utilize jQuery you can use the $.parseJSON() method. Documentation here
For prototype use the .evalJSON() method. Documentation here
JSON.parse has a native implementation in most modern browsers and you can shim it using the implementation on the JSON homepage that Quentin indicated.
Don't use eval for this. A collection of libraries for parsing JSON is listed near the end of the JSON homepage, there are a couple for JavaScript including json2.js which is the usual choice.
Manipulating the data structure has nothing to do with parsing JSON though. If you really want to transform it like then then you'd want something like (untested):
var newObj = [];
for (keys) in myObj) {
newObj.push([key].concat(myObj[key])
}

regular expression to filter out part of key value in a json string

I have the following JSON string as part of a log line.
cells : {"Lac":"7824","CntryISO":"us","NetTyp":"GSM","NetOp":"310260","Cid":"11983"}
I want to filter out to the following format: {"Lac":"7824","Cid":"11983"}.
How can do this using regular expression ? in Javascript or Python ?
the keys are constant strings(Lac, CntryISO, ...), but the value strings are varying.
Why don't you just delete them in JavaScript?
var myJson = {"Lac":"7824","CntryISO":"us","NetTyp":"GSM","NetOp":"310260","Cid":"11983"};
delete myJson.Lac;
delete myJson.cId;
To expand and explain #alex answer:
JSON is a nested multi dimensional structure. Simply filtering the "string-ifiyed form of a Javascript object" (aka JSON) will work in very simple cases, but will rapidly fail when the structure is no longer flat or it starts to get complex with escaped fields, etc.
At that point you will need proper parsing logic. This is nicely supplied by Javascript itself, to quote #alexes code:
var myJson = {"Lac":"7824","CntryISO":"us","NetTyp":"GSM","NetOp":"310260","Cid":"11983"};
delete myJson.Lac;
delete myJson.cId;
Or, if you want to use python, the json module will work just fine:
http://docs.python.org/library/json.html
Good luck! :)
Why would you want to use regex for this when you can just use a JSON parser/serializer? Try cjson in Python if you are concerned about speed, it is faster than 'json' module in the Python standard library.

What can I do with JSON?

I want to, in brief, find out about what I can do with JSON; whether it is an alternative for JavaScript or what?
JSON is short for JavaScript Object Notation. It is a data format used for passing around data, modeled after the Javascript syntax for object/list literals. It is not a programming language, but rather a data markup language.
It's just a data format that converts data structures such as objects & arrays into a string representation. It uses the same format as javascript and is very easy to work with in ajax based applications because of this.
What can you do with json? anything that any other major data format can do. It's just data. What you can do with it is up to you.
JSON (an acronym for JavaScript Object Notation) is a lightweight text-based open standard designed for human-readable data interchange. It is derived from the JavaScript programming language for representing simple data structures and associative arrays, called objects
JSON is built on two structures:
A collection of name/value pairs.
An ordered list of values.
For more on JSON
In a brief JSON is JavaScript Object Notation. Which for example instead of doing:
var obj = new Object( );
obj.arr = new Array( );
obj.name = new String ( "Jhon Doe");
You can do:
var obj = { name: "Jhon Doe", arr: [1,2,3,4]};
So once browser will receive or meet some peace of JSON it would be able to compile it into Javascript object, so you will be able to use itt later in the code and reference to it.

Categories

Resources