I have two web services generating JSON output. Both services are using different technologies but are supposed to generate the exact same output.
I want to check if this output is exactly the same in the browser environment. I would really prefer to simple compare them as string, but the JSON output is not sorted.
I can convert JSON string to objects and then iterate over their keys to check the equivalence but that is basically a n^2 algorithm.
I was wondering if there is any quicker or better way. Something that browser environment already provides.
At the moment there is no such method provided by the browsers to do a deep comparison. WE have to do it ourselves or using some non native library.
Related
I’m new to data structure and I’m learning it in Javascript.
My Question is:
Why do we need hash tables when we 've objects in javascript?
Can anybody give me a situation where hash tables will be more useful than objects?
"Hashtable" is called different things in different languages. Java has Hashtable and HashMap, Ruby has Hash, Python has dict... in JavaScript, it's called Map.
Objects' keys are limited to strings; Map keys can be anything.
Objects support inheritance; a Map only contains what is specifically put into it.
Think you means Map instead of HashTable. IMHO Map may be more useful and perform better if you need one of that:
keep order of insertions of key/value pairs;
frequent additional and removal;
key which not String/Symbol.
I think you can obtain more information at MDN
The MDN docs on this are quite helpful: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Objects_and_maps_compared
Most notably, using a map gives you the advantage of using anything as a key, maps retain order, and may perform better when constantly adding and removing values.
I recently found out that JSON values can only store string, number, object, array, true, false or null. But from my understanding, JSON is how Javascript represents its objects internally. I don't understand how it is possible to store Javascript objects as JSON if most objects have methods, which are functions? Aren't functions objects? What the heck are functions in my Javascript interpreter's (Node.js) opinion and how does it represent them? Thanks!
JSON is a string interchange format. It stands for JavaScript Object Notation. It was invented long after Javascript and has nothing at all to do with how Javascript stores data internally.
JSON is typically used as an interchange format or storage format. One would take some Javascript data, serialize it to the JSON format and take the resulting string and send it to another process or computer or save it in some sort of storage.
The recipient of the JSON can then parse it back into whatever their local data is. JSON is even used to send data from a Javascript program to a program written in another language (Python, Ruby, C++, etc...).
Functions have no connection at all to JSON. They are not stored in JSON. Their internal storage format inside the JS interpreter is specific to whatever interpreter implementation and is not accessible to the outside world or governed by any standard. It's an implementation detail for any Javascript engine and they can do it however they want and each interpreter likely has it's own implmentation or variation. I don't know of any reason why it would matter to your Javascript code.
I recently found out that JSON values can only store string, number, object, array, true, false or null. But from my understanding, JSON is how Javascript represents its objects internally.
That is not correct. JSON is not something that the Javascript interpreter uses for its objects internally. Internal object formats are specific to a particular Javascript interpreter and are not accessible to Javascript code, nor really relevant when writing code.
I don't understand how it is possible to store Javascript objects as JSON if most objects have methods, which are functions?
Javascript does not use JSON for internal storage so it has nothing at all to do with the internal implementation of Javascript data types.
Aren't functions objects?
Yes, but they have nothing to do with JSON.
What the heck are functions in my Javascript interpreter's (Node.js) opinion and how does it represent them?
Each JS interpreter has its own internal implementation/storage for functions. It is not governed by any standard and is largely irrelevant to how you write code in Javascript.
If you had some reason to want to know how a specific Javascript implementation stores its variables internally, you would have to look into the source code. The V8 implementation from Google (used in Chrome and node.js) and the Firefox implementation from Mozilla are both open source and you could dive into that code (it would be mostly C++ code).
This can get pretty complicated because some data types such as Arrays are stored in a variety of different formats depending upon the structure of the array. I believe V8 has at least three storage formats for arrays depending upon whether the array is compacted or sparse and based on its overall size. This is to optimize for both memory consumption and run-time performance.
Likewise properties on objects may be arranged in highly optimized storage formats if the interpreter has advance information from the code about what is being used and what is not, compared to arbitrary programmatically generated properties.
FYI, you can find the Google repository here: https://chromium.googlesource.com/v8/v8.git and the Mozilla code here: https://hg.mozilla.org/.
I am using node.js as my server platform and I need to process a non sparse array of 65,000 items.
Javascript arrays are not true arrays, but actually hashes. Index access is accompagnied with conversion of the index to string and then doing a hash lookup. (see the Arrays section in http://www.crockford.com/javascript/survey.html).
So, my question is this. Does node.js implement a real array? The one that does cost us to resize or delete items, but with the true random access without any index-to-string-then-hash-lookup ?
Thanks.
EDIT
I may be asking for too much, but my array stores Javascript objects. Not numbers. And I cannot break it into many typed arrays, each holding number primitives or strings, because the objects have nested subobjects. Trying to use typed arrays will result in an unmaintainable code.
EDIT2
I must be missing something. Why does it have to be all or nothing? Either true Javascript with no true arrays or a C style extension with no Javascript benefits. Does having a true array of Javascript (untyped) objects contradicts the nature of Javascript in anyway? Java and C# have List<Object> which is essentially what I am looking for. C# even closer with List<DynamicObject>.
Node.js has the Javascript typed arrays: Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array.
I think they are what you are asking for.
Node.js does offer a Buffer class that is probably what you're looking for:
A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized.
Not intrinsically, no.
However depending on your level of expertise, you could write a "true" array extension using Node's C/C++ extension facility. See http://nodejs.org/api/addons.html
You want to use Low Level JavaScript (LLJS) to manipulate everything directly in C-style.
http://mbebenita.github.com/LLJS/
Notice that according to the link above, an LLJS array is more like the array you are looking for (true C-like array), rather than a Javascript array.
There is an implementation for LLJS in Node.js available , so maybe you do not have to write your own node.js C extension. Perhaps this implementation will do the trick: https://github.com/mbebenita/LLJS
I am in need of a Javascript data structure which will allow me to insert strings and search for strings efficiently. I have been looking around and the only data structures I have come across are objects and arrays. Objects are more used for encapsulation and cannot really be used for searching and using arrays can be slow. Are there any other data structures that will allow me to insert and search strings efficiently? Right now at best I could do a binary search on an array. Any other ideas? Thanks.
Objects are more used for encapsulation and cannot really be used for
searching
That was true in classical languages, not so true in JS.
var obj = { memberone: "value1" }
var value = obj["memberone"];
//value === "value1"
Objects can be searched in JS. Bear with me...
and using arrays can be slow.
Yes, can be - but don't have to be.
Are there any other data structures that will allow me to insert and
search strings efficiently?
Data structures? No. Again that is a classical perspective. In JS, it is different.
Check out _underscore.js.
It is 4k min gzip.
It provides a number of advanced iterator helpers (so you don't have to)
It provides templates to display your data to screen efficently.
It will benefit the rest of your development, maintenance, and implementations.
This is a good example of JS flexibility.
Hope that helps.
All the best!
Nash
There are some more I found after some goggling,
Javascript data structures - a collection object
One more thing you can use json objects and its JavaScript API to manipulate same. Please refer same here
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.