What can I do with JSON? - javascript

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.

Related

Will JSON Evolve to Have Native Support for Ecmascript Map Objects?

Are there any formal proposals, in progress, that address a backwards-compatible evolution to JSON's current treatment of Map objects?
For example, let say you want to convert a Map to JSON and then write it to file:
let map = new Map();
map.set(1, "A");
map.set(2, "B");
map.set(3, "C");
// Convert map to an "array of 2-element arrays":
let arrayFromMap = [... map];
let json = JSON.stringify(arrayFromMap);
writeJSONtoFile(json,"path/to/jsonFile.json");
So now we have a JSON file sitting on the disk. The issue is that, the code that ultimately reads this file has no knowledge that it contains a Map object unless we give that code-file that awareness. There is nothing inherent in JSON to explicitly indicate Map instead of a "array of 2-element arrays". For example, code not having this awareness might do this:
let json = readJSONfromFile("path/to/jsonFile.json");
let parsedJSON = JSON.parse(json);
console.log(parsedJSON); // outputs an "array of 2-element arrays"
However, if the the code writer gives the code awareness (that the original type was a Map) the file can be converted back to a Map:
let json = readJSONfromFile("path/to/jsonFile.json");
let map = new Map(JSON.parse(json));
This same awareness isn't necessary for these built-ins: Objects and Arrays.
In the example above, this "awareness" requirement isn't too burdensome. However, imagine a large hierarchy that contains both Maps and "arrays of 2-element arrays" that are not intended to be Maps. This "awareness burden" has now extended to each nested Map within the hierarchy.
Are there any formal proposals, in progress, that address a backwards-compatible evolution to JSON's current treatment of Map objects?
No, because JSON notation, while it originated with Javascript, is widely used in a very large number of languages, but a Javascript Map only has meaning within the context of Javascript.
Any sort of change to JSON notation to allow for the serialization and deserialization of objects that only have meaning in Javascript would make that JSON format incompatible with most other languages.
This isn't to say that a custom parser based on JSON couldn't be written to properly serialize and deserialize Maps, but such a thing would only be based on JSON, rather than being an addition to the JSON standard.
Like CertainPerformance's answer, it's important that JSON remain as abstract as possible for the sake of portability and compatibility.
Wanted to add that keeping the integrity of the Map objects inside of a JSON object is really simple anyway without having to add a new specification; like adding a flag per Map during serialization.

Reading JSON objects from javascript file using JINT

I've been supplied with a javascript file containing two JSON objects such as this.
var languages = {"Languages":["English","Cymraeg","Deutsch"]};
var labels = [{"$JOB":["Job","Orchwyl","Auftrag",]},{"$JOB_NO":["Job Number","Rhiforchwyl","Auftragsnummer"]}];
I need to serialise the two JSON objects into something I can manipulate within .NET. I'm using JINT to get the two values from the file like this.
Engine js = new Engine();
js.Execute(fileContents);
languages = js.GetValue("languages");
labels = js.GetValue("labels");
But I can't do anything with the two values now. I can't parse the JSON, the values just come out as a strange object array where I can't actually determine the values.
Any suggestions on how I can get access to the JSON objects?
There is no JSON here.
This is javascript code, that creates javascript objects when it's evaluated.
Now, you can convert that javascript object into a JSON string.
The simplest way I found, was to have JINT do it for me, but I'm no expert in Jint, there might be better ways.
// Run javascript, inside the interpreter, to create JSON strings
js.Execute("languages = JSON.stringify(languages)");
js.Execute("labels = JSON.stringify(labels)");
// Extract the strings from the JS environment, into your c# code as strings
// Now, you can deserialize them as normal JSON
var languagesJsonString = js.GetValue("languages").AsString();
var labelsJsonString = js.GetValue("labels").AsString();

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.

Newbie: object or hash?

If I define something like following:
var groups={
'group_one': ['red','green','blue'],
'group_two': ['yellow','black'],
'group_three': ['white', 'pink','purple','orange']
}
Is it an normal js object or an hash table? If it is not a hash table, then how does the Javascript hash table look like?
I can access a group by:
my_group=groups['group_two']
It is an object, that's how specification refers to it. An object is a data type in JavaScript.
A hash table [Wikipedia] is a data structure for which you could use objects, but it does not handle duplicate keys well (it just overrides the entry). You can provide your own implementation, for example have a look at the Hash Map implementation from the Google Closure Library.
Your groups variable refers to a perfectly normal object, which like all normal javascript objects are associative arrays that map property names to property values. These are often implemented as hashtables under the hood.
As far as I know, JavaScript does not have hash tables as such. You have good old zero-based numeric arrays:
var a = ["foo", "bar"];
alert(a[0]); // "foo"
... and you have objects:
var b = {
x: "foo",
y: "bar
};
alert(b.x); // "foo"
Arrays are sorted by key and cannot have gaps. Objects are not sorted. And they share the square brackets syntax:
alert(a[0]);
alert(b[x]); // same as b.x
I suppose that JavaScript engines make heavy use of hash tables in their internals but JavaScript engines are not normally written in JavaScript ;-)
If you want the typical capabilities of a hash table, where you provide a key and data and you can then get the data back by providing the key, then a javascript object provides that capability using properties on the object.
Internally to the javascript engine is a property lookup algorithm for objects that likely resembles what is used with a hash table (though the particular implementation is not important as it has the appropriate function).
There is no separate hash table in the language. One could be implemented, but there is rarely a point as an object typically provides what is needed.
In your data:
var groups= {
'group_one': ['red','green','blue'],
'group_two': ['yellow','black'],
'group_three': ['white', 'pink','purple','orange']
}
You can access data in the future with:
groups.group_one
or
groups['group_one']
and both will evaluate to:
['red','green','blue']

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