Compare JSON structures - javascript

I want to compare received JSON data to a JSON 'template', and if it differs in structure (not in data itself) then do something,like discarding that JSON.
Template:
{
"data":{
"id":"1",
"cmd":"34"
}
Succesfull Json:
{
"data":{
"id":"15",
"cmd":"4"
}
Unsuccesfull Json:
{
"data":{
"id":"15"
}
This is only an example, the JSON to evaluate is going to be larger, and I want to avoid checking if each property exists. (This is possible in other languages, hence this question)

It sounds like you're looking for JSON Schema or other similar tools.
JavaScript itself doesn't provide anything built-in to do this for you. So you'll need an already-written tool to do it (such as JSON Schema) or you'll have to do it yourself, checking the existence and (depending on how strict you want to be) type of each property in the received JSON. You can do that either after parsing or during parsing by hooking into the parsing process via a "reviver" function you pass into JSON.parse, but either way is going to require doing the checks. (Given the inside-to-outside way JSON.parse works, I suspect using a reviver for this would be quite hard though. Much better to use a recursive function on the parsed data afterward.)

I would recommend converting it to object JSON.parse(), so you can use javascript API.
If your structure gets more robust in the future (more levels etc), you would be still able to do deep compares. Libraries like Immutable.js will come handy, as it used to compare complex states in React applications.

I recently faced this problem as well. I needed to make some comparisons on some objects (should work for JSON as well). I wrote a package for doing this that might come in handy for people facing this issue in the future (bit late for the topic starter).
https://www.npmjs.com/package/js-object-compare

Related

Nodejs Couchbase deserialize date property from document

I'm saving in Couchbase a document which has javascript Date values, and wish to get it exactly the same, not as string '2016-01-02T12:13:14Z'.
Found a way to achieve this using plain Javascript, by using the second parameter of JSON.parse , but Couchbase does the deserialization internally and can't really use this.
Is there any way to disable the Couchbase deserialization, and to avoid doing JSON.stringify + JSON.parse and neither deep-walking the object?
bucket.get(key, (err, result) => {
if (err) {
//deal with error here
} else {
//here "result.value" is already deserialized
done(result.value);
}
});
As you probably know, JSON and Date object handling can be a bit specific depending on what you're trying to do. We tend to stick to the defaults. What you're looking for is a fairly advanced use case. At the moment, we don't have direct support for changing the way we do that parsing.
However, there is an interface for this. It's called a "transcoder" and it lets you be very specific about how you want to handle converting incoming data to what is stored. I don't have an example that shows quite what you want to do, but a good place to start looking for this at a lower layer is shown in the tests.
It might be easier, however, to just treat whatever you're storing differently at the application level. From my read of the revivier parameter you pointed to, that'd be only at time of retrieval. There's nothing stopping you from wrapping that get() and then mutating the object before passing it along to the next layer at very low cost I do believe.

Flash Twitter API with JSON

I have read a lot about parsing JSON with Actionscript. Originally it was said to use this library. http://code.google.com/p/as3corelib/ but it seems Flash Player 11 has native support for it now.
My problem is that I cannot find examples or help that takes you from beginning to end of the process. Everything I have read seems to start in the middle. I have no real experience with JSON so this is a problem. I don't even know how to point ActionScript to the JSON file it needs to read.
I have a project with a tight deadline that requires me to read twitter through JSON. I need to get the three most recent tweets, along with the user who posted it, their twitter name and the time those tweets were posted.
The back end to this is already set up I believe by the development team here, therefor my JSON files or XML just needs to be pointed to and then I need to display the values in the interface text boxes I have already designed and created.
Any help will be greatly appreciated...I do know that there are a lot of threads on here I just do not understand them as they all have some understanding of it to begin with.
You need to:
Load the data, whatever it is.
Parse the data from a particular format.
For this you would normally:
Use URLLoader class to load any data. (Just go to the language reference and look into example of how to use this class).
Use whatever parser to parse the particular format that you need. http://help.adobe.com/en_US/FlashPlatform/beta/reference/actionscript/3/JSON.html this is the reference to JSON API, it also shows usage examples. I'm not aware of these API being in production version of the player, still there might be quite a bit of FP 10.X players out there, so I'd have a fallback JSON parser, but I would recommend using this library: http://www.blooddy.by/en/crypto/ over as3corelib because it is faster. The built-in API are no different from those you would find in browser, so if you look up JSON JavaScript entries, the use should be in general similar to Flash.
After you parse JSON format, you will end up with a number of objects of the following types: Object, Array, Boolean, Number, String. It has also literals to mean null and undefined. Basically, you will be working with native to Flash data structures, you only should take extra care because they will be dynamically constructed, meaning you may not make assumption about existence of parts of the data - you must always check the availability.
wvxvw's answer is good, but I think skips over a to be desired explanation of what JSON itself is. JSON is plain text, javascript object notation, when you read the text on screen it looks something like this
http://www.json.org/example.html
you can see a side by side JSON and XML (both plain text formats) essentially JSON is a bunch of name value pairs.
When you use JSON.parse("your JSON string goes here") it will do the conversions to AS3 "dynamic objects" which are just plain objects (whose properties can be assigned without previously being defined, hence dynamic). But to make a long story short, take the example you see in the link above, copy and paste the JSON as a string variable in AS3, use
var str:String = '{"glossary": {"title": "example glossary","GlossDiv": {"title": "S","GlossList": {"GlossEntry": {"ID": "SGML","SortAs": "SGML","GlossTerm": "Standard Generalized Markup Language","Acronym": "SGML","Abbrev": "ISO 8879:1986","GlossDef": {"para": "A meta-markup language, used to create markup languages such as DocBook.","GlossSeeAlso": ["GML", "XML"]},"GlossSee": "markup"}}}}}';
var test:Object = JSON.parse(str);
method on the string, store it in a variable and use the debugger to see what the resulting object is. As far as I know there's really nothing else to JSON it's simply this format for storing data (you can't use E4X on it since it's not XML based and because of that it's slightly more concise than XML, no closing tags, but in my opionion slightly less readable... but is valid javascript). For a nice break-down of the performance gains/losses between AMF, JSON and XML check out this page: http://www.jamesward.com/census2/ Though many times you don't have a choice with regard to the delivery message format or protocol being used if you're not building the service, it's good to understand what the performance costs of them are.

How to create a tree representation of generic JSON data in HTML?

I have some data stored in JSON format. I would like to be able to display it in a browser as a dynamic tree structure in a similar way MongoVUE presents the mondodb documents:
Screenshot
I have found a very nice jquery plugin, called jsTree. Unfortunately, in order to process JSON documents it requires data to have a very specific verbose (and redundant, in my opinion) structure: link. Using it means significant modifications of my json documents. I am rather searching for a tool that is able to build the tree automagically, without making severe manual adjustments to the data, yet allowing me to potentially apply some modifications to the view, if I would need to.
The tool at json.bloople.net makes something similar using a table, but because I have several levels of nested documents, the output looks very bloated. Moreover, the structure is not dynamically collapsible.
I would appreciate any hints regarding the right tools to do the job, including both those that might require (automated!) pre-processing of JSON data in Java/Groovy or pure JavaScript-based solution.
This is just a simple example of how you could output a tree like JSON structure in html. http://jsfiddle.net/K2ZQQ/1/ (see here for browser support for white-space). Note that the second parameter to JSON.stringify is a replacer function:
From http://msdn.microsoft.com/en-us/library/ie/cc836459(v=vs.94).aspx
If replacer is a function, JSON.stringify calls the function, passing
in the key and value of each member. The return value is used instead
of the original value. If the function returns undefined, the member
is excluded. The key for the root object is an empty string: "".
So if you need to add any further modifications to the dislpay of your JSON tree the replacer function may be of help.

JSON vs Array and is there a way to convert one to the other then back again

I know in concept, or reality even they are essentially one in the same. However I know working with JSON objects (as of the time of writing this at least). That Altering the data within a given set of objects isn't the easiest thing. Of course I could be wrong, there could be an easy means of doing it all JSON. Which leads me to my actual question.
I am working almost entirely with JSON formatted Objects. Most of which I need to update frequently for storage for later use. Personally I would like to avoid sending data to and from the server to rebuild the JSON set of Objects every time. So I guess in all I am wondering if there is an equivalent to something like PHP's json_encode, json_decode? Either natively in JavaScript or through the jQuery Lib. and If not, how can I achieve something like that cause I feel (again at the moment) working with array's vs a JSON object is much easier (correct me if I am wrong).
The reason why this question pops up in your mind is because you don't understand neither Javascript or JSON enough.
The Javascript array is always the numerical array. There is no associate array in JavaScript like the one you get in PHP using json_decode(json, true);. When people talking about associate array in JavaScript, they are in fact using JavaScript objects and it's properties, i.e.,
var my_so_called_array = {};
my_so_called_array['first_item'] = 'hello world';
alert(my_so_called_array['first_item']); // 'hello world'
alert(my_so_called_array.first_item); // also 'hello world'
One of the best about JSON is that the syntax is a subset of the object literal notation. That means JSON string itself is valid code for representing the "associate array" in Javascript. The "conversion" couldn't be simpler, just eval() the string as code will do:
var my_data = eval(json_string);
Or, use jQuery.parseJSON() or JSON.parse():
var my_data = jQuery.parseJSON(json_string);
var my_data = JSON.parse(json_string);
The reason people prefer using jQuery.parseJSON() or JSON.parse() over eval() is because eval is evil:
It's slower
It doesn't check the validity of the JSON code, makes it suspect-able to injection attack.
Does the above explanation answer your question? You can find more information about JSON at www.json.org.
All modern browsers support JSON.stringify() and JSON.parse().
If you have to support older browsers, you can use jQuery's $.parseJSON().

Why is JSON important?

I've only recently heard about JSON (Javascript Object Notation).
Can anybody explain why it is considered (by some websites/blogs/etc) to be important?
We already have XML, why is JSON better (apart from being 'native to Javascript')?
Edit: Hmm, the main answer theme seems to be 'it is smaller'. However, the fact that it allows data fetching across domains, seems important to me. Or is this in practice not (yet) much used?
XML has several drawbacks:
It's heavy!
It provides a hierarchical representation of content which is not exactly the same as (but pretty much similar to) Javascript object model.
Javascript is available everywhere. Without any external parsers, you can process JSONs directly with JS interpreter.
Clearly it's not meant to replace XML completely. For JS based Web apps, its advantages can be useful.
JSON is generally much smaller than its XML equivalent. Smaller transfer means faster transfer, which results in a better user experience.
JSON is much more concise. XML:
<person>
<name>John Doe</name>
<tags>
<tag>friend</tag>
<tag>male</tag>
</tags>
</person>
JSON:
{"name": "John Doe", "tags": ["friend", "male"]}
There's fewer overlapping features, too. For example, in XML there's tension between choosing to use elements (as above), versus attributes (<person name="John Doe">).
JSON came into popular use primarily because it offers a way to circumvent the same-origin policy used in web browsers and thereby allow mashups.
Let's say you're writing a web service on domain A. You can't load XML data from domain B and parse it because the only way to do that would be XMLHttpRequest, and XMLHttpRequest was originally limited by the same-origin policy to talking to only URLs at the same domain as the containing page.
It turns out that for a variety of reasons, you are allowed to request <script> tags across origins. Clever people realized this was a good way to work around the limitation with XMLHttpRequest. Instead of the server returning XML, it can return a series of JavaScript object and array literals.
(bonus question left as an exercise to the reader: why is <script src="..."> allowed across domains without server opt-in but XHR isn't?)
Of course, returning a <script> which consists of nothing more than object literals is not useful because without assigning the values to some variable, you can't do anything with it. Thus, most services use a variant of JSON, called JSONP (http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/).
With the rise in popularity of mashups, people realized that JSON was a convenient data interchange format in general, especially when JavaScript is one end of the channel. For example, JSON is used extensively in Chromium, even in cases where C++ is on both sides. It's just a nice lightweight way to represent simple data, that good parsers exist for in many languages.
Amusingly, using <script> tags to do mashups is incredibly insecure because it is essentially XSS'ing yourself on purpose. So native JSON (http://ejohn.org/blog/native-json-support-is-required/) had to be introduced, which obviates the original benefits of the format. But by that time, it was already super popular :)
If you are working in Javascript, it is much easier to us JSON. This is because JSON can be directly evaluated into a Javascript object, which is much easier to work with than the DOM.
Borrowing and slightly altering the XML and JSON from above
XML:
<person>
<name>John Doe</name>
<tag>friend</tag>
<tag>male</tag>
</person>
JSON:
{ person: {"name": "John Doe", "tag": ["friend", "male"]} }
If you wanted to get the second tag object with XML, you'd need to use the powerful but verbose DOM apis:
var tag2=xmlObj.getElementsByTagName("person")[0].getElementsByTagName("tag")[1];
Whereas with a Javascript object that came in via JSON, you could simply use:
var tag2=jsonObj.person.tag[1];
Of course, Jquery makes the DOM example much simpler:
var tag2=$("person tag",xmlObj).get(1);
However, JSON just "fits" in a Javascript world. If you work with it for a while, you will find that you have much less mental overhead than involving XML based data.
All the above examples ignore the possibility that one or more nodes are available, duplicated, or the possibility that the node has just one or no children. However, to illustrate the native-ness of JSON, to do this with the jsonObj, you'd just have to:
var tag2=(jsonObj.person && jsonObj.person.tags && jsonObj.person.tags.sort && jsonObj.person.tags.length==2 ? jsonObj.person.tags[1] : null);
(some people might not like that long of ternary, but it works). But XML would be (in my opinion) nastier (I don't think you'd want to go the ternary approach because you'd keep calling the dom methods which may have to do the work over again depending on implementation):
var tag2=null;
var persons=xmlObj.getElementsByTagName("person");
if(persons.length==1) {
var tags=persons[0].getElementsByTagName("tag");
if(tags.length==2) { tag2=tags[1]; }
}
Jquery (untested):
var tag2=$("person:only-child tag:nth-child(1)",xmlObj).get(0);
These web pages may help:
JSON - The Fat Free alternative to xml
Why JSON is Important to You!
It depends on what you are going to do. There are a lot of answers here that prefer JSON over XML. If you take a deeper look there isn't a big difference.
If you have a tree of objects you get only tree of javascript objects back. If you take a look at the tension to use OOP style access than turns back on you. Assume you have an object of type A, B ,C that are constructed in a tree. You can easily enable them to be serialzed to JSON. If you read them back in you only get a tree of javascript objects. To reconstruct your A, B, C you have to stuff the values manually into manually created objects or you doing some hacks. Sound like parsing XML and creating objects? Well, yes :)
This days only the newest browsers come with native support for JSON. To support more browsers you have two options: a) you load a json paraser in javascript that helps you parsing. So, how fat does this sound regarding fatreeness? The other option as I often see is eval. You can just do eval() on a JSON String to get the objects. But that introduces a whole new set of security problems. JSON is specified so it can't contain functions. If you are not checking the objects for function someone can easily send you code that is being executed.
So it might depend on what you like more: JSON or XML. The biggest difference is propably the ways of accessing things, be it script tags XMLHTTPRequest... I would decide upon this what to use. In my opinion if there would be proper support for XPATH in the browsers I would often decide for XML to use. But the fashion is directed towards json and loading additional json parsers in javascript.
If you can't decide and you know you need something really powerful you ight have to take a look at YAML. Reading about YAML is very interesting to get more insight in the topic. But it really depends on what you are trying to do.
JSON is a way to serialize data in Javascript objects. The syntax is taken from the language, so it should be familiar to the developer dealing with Javascript, and -- being the stringification of an object -- it's a more-natural serialization method for interaction within the browser than a full-fledged XML derivative (with all the arbitrary design decisions that implies).
It's light and intuitive.
JSON's a text-based object serialization format that's more lightweight than XML and that directly integrates with JavaScript's object model. That's most of its advantages right there.
Its disadvantages (compared to XML) are, roughly: fewer available tools (forget about standard validation and/or transformation, to say nothing of syntax highlighting or well-formedness checking in most editors), less likely to be human-readable (there's huge variations in the readability of both JSON and XML, so that's a necessarily fuzzy statement), tight integration with JavaScript makes for not-so-tight integration with other environments.
It's not that it is better, but that it can tie many things together to allow seamless data transfer without manual parsing!
For example javascript -> C# web service -> javascript

Categories

Resources