how do parse JSON in javascript? - 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])
}

Related

How to convert a JSON string to a JSON string with a different structure

I am building an application where data is retrieved from a third party system as a JSON string. I need to convert this JSON string to another JSON string with a different structure such that it can be used with pre-existing functions defined in a internal Javascript library.
Ideally I want to be able to perform this conversion on the client machine using Javascript.
I have looked at JSONT as a means of achieving this but that project does not appear to be actively maintained:
http://goessner.net/articles/jsont/
Is there a de facto way of achieving this? Or do I have to roll my own mapping code?
You shouldn't be passing JSON into an internal JavaScript library. You should parse the JSON into a JS object, then iterate over it, transforming it into the new format
Example
var json = '[{"a": 1:, "b": 2}, {"a": 4:, "b": 5}]';
var jsObj = JSON.parse(json);
// Transform property a into aa and property b into bb
var transformed = jsObj.map(function(obj){
return {
aa: obj.a,
bb: obj.b
}
});
// transformed = [{aa:1, bb:2},{aa:4, bb:5}]
If you really want JSON you'd just call JSON.stringify(transformed)
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map
Here's another answer with an even more complicated transformation How to make a jquery Datatable array out of standard json?
From what I can tell from the home page, the JSONT project is about transforming JSON into entirely different formats anyway (i.e. JSON => HTML).
It's going to be a lot simpler to write your own mapping code, possibly just as a from_json() method on the object you're creating (so YourSpecialObject.from_json(input); returns an instance of that object generated from the JSON data).
From your question, I'm not sure if this fits your use case, but hopefully someone else will have a better answer soon.
Another option is using XSLT. As there are SAX readers and writers for JSON, you can write happily use XSLT with JSON. There's no horrific JSON to XML and back conversion needs to go on. See: http://www.gerixsoft.com/blog/json/xslt4json
I can definitely see the irony in using a XML based language to tranform JSON - but it seems like a good option.
Otherwise you're probably best of writing your own mapping code.

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)

Javascript stringed array into an actual array

Ok. So the title sounds confusing but that's probably the best way to describe it.
I'm using the TextExt jQuery plugin to create a tag list in a form. However the plugin creates an array in a string when submitted. eg. "["this","that","other"]".
How can I convert this to an actual array? ["this","that","other"]
Cue really simple answer I completely overlooked.
Since you are using jQuery you can just pass it through jQuery.parseJSON like this:
var array = jQuery.parseJSON('["this","that","other"]')
Looks like JSON. So then use JSON.parse(), or better jQuery.parseJSON() when you already have jQuery inlcuded.

Rendering json using jquery

I need a simple example that has a json data and I have to parse it and render in html. Can someone suggest me a simple way to do this?
You can create a string from an object in JavaScript like this...
var jsonString = JSON.stringify(myJsonObject);
Then you can use that string to apply to a html element. For example...
document.getElementById('myDivID').innerText = jsonString;
With JQuery you can update a DIV with the following...
$("#MyDiv").html(jsonString);
I'm not entirely sure what you are asking. You do not have to use jQuery specifically to parse the object. All you need is standard JavaScript.
Given a JSON string, you can parse it into a JavaScript object using the JSON library
var myJSONObject = JSON.parse(myJSONString);
Or into a string from an object:
var myJSONString= JSON.stringify(myJSONObject);
If you are looking for the individual items of a JSON structure, then you can use a for loop:
for (var key in myJSONObject){
alert(myJSONObject[key]);
}
I've alerted myJSONObject[key] in the above, however, you can do what you want with it.
You would use jQuery to select out the container into which you wanted the info to be displayed, as suggested in usefan's answer.

Json(/hash) to ruby object?

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/

Categories

Resources