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/.
Related
I've been reading up on JSON and serialization, from what I understand JSON is a format often used for transferring data over a network e.g. from/to a web server or storing the data to disk.
The data could be strings, numbers, objects etc. I haven't found a clear explanation for why the serialization is needed, for instance when sending a string to a web server or saving it to disk, isn't the string already stored as a series of bits and bytes by the computer, isn't this the most basic form for the data? so why can't these be sent/stored as they are?
Why does it need to be stringified into JSON i.e. serialised, which turns it into a string?
To be clear, I'm asking why it's needed and a simple clear explanation for that.
Thanks
Broadly speaking serialization does two important, mostly independent jobs:
collects all the information into a single "chunk" (stream) of data that's self-contained and
turns all the information into an agreed-on format (usually optimized for either compactness or ease of parsing)
#1 is important because a single object with many properties and sub-object can be spread all over the memory of a running program.
For example a JavaScript runtime could have a dedicated memory pool for strings constants. Then an object that uses some constant as a key would just reference into that pool from its data structure. That means that the object is no longer in a single self-contained block in memory: it's spread out over multiple areas. This kind of spreading-out is actually the norm: objects don't usually contain complex data directly and depending on the language even "primitive" values such as number could be stored as references to another place in memory.
#2 is important mostly because the format used to quickly access data in-memory might not be suitable to transfer (because it might contain unnecessary redundancy or memory pointers that don't make any sense when transferred to another computer, which partially ties to reason #1).
An example of that would be a map (or dictionary): the in-memory representation will usually involve multiple buckets that hold hashed-values and some kind of collision-handling structure inside those buckets (a linked list or a tree, for example). That structure helps with efficient access to separate keys, but transferring that structure directly over the wire is pointless: it's very easy to re-build and there's no guarantee that the receiving end uses the exact same way to represent a map. So instead we just send each key and the associated value and let the receiving end deal with re-constructing any data structures it needs for efficient access.
The simple reason is that data can be stored differently in memory on different computers, or even by programs on the same computer written in different programming languages.
Serialization formats like JSON provide a defined way for exchanging data between computers or programs.
Not everyone knows how to parse or interpret those series of bits. Sometimes you need some general structure, some format, that can be passed around so that other people understand what it is you're trying to tell them.
According to http://doc.qt.io/qt-5/qtwebchannel-javascript.html
Furthermore keep in mind that only QML/C++ data types which can be converted to JSON will be (de-)serialized properly and thus accessible to HTML clients.
What are those data types which can be converted to JSON?
Is the QJsonObject or QJsonDocument included on it?
You can look into the documentation for classes such as QJsonValue and QJsonObject and see which types and classes can be used by constructors or by from*(...) functions, which are usually static and ask for a QVariant/QVariantHash/QVariantMap.
Given that in Qt JavaScript an array can be converted into a QList<> and an object to a QVariantMap, I would guess those (and basic types such as int, float, string...) should be passed to the C++ side and made into QJson(Value/Object/Array) then.
Depending on what you want, a QJsonObject could be, for example, formatted as a string like this. For further information, JSON support in Qt.
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.
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.
Why does JSON only allow a string to be a key of a pair? Why not other types such as null, number, bool, object, array? Considering JSON is tightly related with JavaScript, could I conclude the reason from JavaScript specification (ECMA-262)? I'm totally a newbie to JavaScript, could you help me to point it out.
The JSON format is deliberately based on a subset of JavaScript object literal syntax and array literal syntax, and JavaScript objects can only have strings as keys - thus JSON keys are strings too. (OK, you can sort of use numbers as JavaScript object keys, but really they get converted to strings.)
Note that the point of JSON is that it is a string representation of data to allow easy exchange between programs written in different languages running on different machines in different environments. If you wanted to use an object as a key then that object would in turn have to be somehow represented as a string for transmission, but then the receiving language would need to be able to use objects as keys and that would mean you'd need a limited subset of JSON for those languages which would just be a mess.
"Considering JSON is a part of JavaScript"
No, it isn't. Newer browsers provide methods for creating and parsing JSON, but they're not part of the language as such except that JSON is a string format and JavaScript can do strings. JSON is always a string representation - it has to be parsed to create an object for use within JavaScript (or other languages) and once that happens JavaScript (or the other languages) treat the resulting object the same as any other object.
(Note also that a particular bit of JSON doesn't necessarily have any keys at all: it could just be an array, like '["one","two","three"]'.)
Main reason according to the discoverer of JSON representation is,
while parsing JSON data, there is a chance/possibility that, key
you are using to refer a value might be a reserved word in your
parsing language.
Refer this talk by Douglas Crockford, who is the discoverer of JSON representation.
Example :
{
id: 1234,
name: "foo",
do: "somthing"
}
Since JSON is a cross language compatibility, We can use this data set in many languages. But, the word do is a keyword in Javascript. It will end up in syntax error while parsing.
Because that is the way the specification was written.