JSON serialization of simple objects is inconsistent - javascript

Every JSON serialization utility or library I've used is seems to be broken, and I cannot get the logical explanation on this.
Let me explain. I run following code in Firebug for JSON libraries for .NET, probably for other languages.
I just check in Firefox, when I run:
var obj1 = "test";
var obj1serialization = JSON.stringify(obj1);
The output is ""test"". But this is invalid JSON object! So when I tried to re-create object from that serialized JSON, it failed, stating that JSON string is incorrect:
var obj2 = JSON.parse(obj1serialization);
Strings are objects. But their serialization in JSON not working. Is there any logical explanation of this situation?

In JSON (unlike several programming languages), strings are not objects, they're primitives (like numbers and booleans). You're asking the serializer to create a JSON fragment. A valid JSON document's top-level item is always an object or an array. If you feed one of those into JSON.stringify, it will produce a valid, complete JSON document.
The fact that most JSON serializers allow fragments is quite useful. The only alternative they'd have would be to throw an exception if you passed something into them that wasn't an object or array.
JSON.parse is more restrictive, requiring that the JSON document you give it be both complete and well-formed. Not all JSON parsing routines are that restrictive, but that one is.

Related

sending Json from JavaScript to codebehind

Output function javascript: (use json.stringify)
"[\"Lighthouse(1).jpg\",\"Penguins(2).jpg\"]"
how convert this output to json in c#.
Is there a function to convert to Json
tanks for answer
There is no problem here, the output data you have shown in the hidden field is in fact valid JSON. Square brackets are used to denote an array of data which is why it is showing here as you are converting a javascript array into JSON. Curly braces which is what you may be thinking of for JSON is used to denote objects in JSON. You can see more on JSON at the w3schools page.
I have tested your JSON string that you have shown in a few JSON decoders for different languages and all convert the data to an array in the native language without any errors.

Use JSON Into An Object Model or Plain JSON

I'm doing a research about the subject of JSON Deserialization Into An Object Model, what do you think about it?
Would you prefer to use JSON from the server as is or converting it to Object Model (concrete JS objects)
What are the benefits of mapping it to Objects and not use the raw JSON, what are the negative aspects ?
What are the performance implications?
Our legacy developer wrote an SDK / DAL with a mapper function that traversing the JSON and make concrete objects,
you can see the implementation here : https://gist.github.com/send2moran/211a2eb19c4a7bf494e8
Would you work with the parsed JSON or prefer to use a mapping function?

JSON Object vs Javascript object [duplicate]

This question already has answers here:
What is the difference between JSON and Object Literal Notation?
(10 answers)
Closed 9 years ago.
I'm a newbie to JS and JSON and trying to understand the difference, I see other threads on this difference but still have few unanswered questions,
I have created 3 objects
Key-vaue pairs in double quotes
Key without quotes but value with quotes
Key-value pairs in single quotes.
Questions.
Asis, is it safe to assume if all the 3 objects are Javascript objects?
How do I determine which one is JSON Object here, when I print the objects in the log, all the objects looks same. Is there a way to determine the JSON Object?
If JSON Objects - key-value pairs are enclosed in double quotes, what does the single quote mean?
Code:
<html>
<head>
<script>
var jsobject = {"fname":"Bob","lname":"Mike"}
console.log(jsobject)
var jsobject = {fname:"Bob",lname:"Mike"}
console.log(jsobject)
var jsobject = {'fname':'Bob','lname':'Mike'}
console.log(jsobject)
</script>
</head>
<body>
</body>
</html>
I think you're confusing syntax and data.
Any number of technologies can have very similar syntax, yet that similar syntax may be used for entirely different purposes, and for creating vastly different data.
when we talk about JSON, we're talking about textual data with a Unicode encoding that follows a character syntax that is meant to be used as a data transferral mechanism. That JSON data can be transferred into a wide variety of different programming environments, parsed, and then converted into actual object structures that make sense for the environment.
The reason that it was named "JavaScript Object Notation" is that its notation is largely patterned after a subset of the literal syntax used in JavaScript programs to create objects and primitive values. Sadly, this naming contributes to the confusion of JavaScript developers.
So to determine if you're dealing with JSON, what's ultimately the most important thing to think about is whether what you're doing will result in the creation of Unicode data that follows the rules of JSON syntax.
Take this example:
var foo = {"bar":"baz"};
Is that JSON? Well if it runs in a JavaScript program, it will be evaluated, and foo will hold a reference to some memory that is not Unicode text data.
Sure we could isolate the {"bar":"baz"} part of the code, and transfer it into its own text file that is encoded as Unicode, but then we're really not dealing with the same example anymore.
So let's say we did that. We open our text editor, make sure it's set up for Unicode encoding, and then paste in that one part of the above code. So now the entirety of our text file is this:
{"bar":"baz"}
Now we can correctly say that we have JSON data. What if I added a ; to the end?
{"bar":"baz"};
It's no longer JSON because it has been corrupted by the ; which is not allowed. Again, we could play around with calling it JSON except for whatever isn't valid, but really it either is or isn't valid in its entirety.
So back to a JavaScript example. Does it every make sense to refer to JSON within the syntax of a JavaScript program? Well take our original example. If we could use some JavaScript syntax to create Unicode data and make it comply with JSON syntax, then yes, we could correctly speak of having JSON in our program.
So does JavaScript let us create Unicode data? Yes, all strings in JavaScript are UTF-16 encoded. Therefore all we need to do is create a string.
var foo = '{"bar":"baz"}';
Now we wouldn't call that entire line JSON, but we could correctly say that the foo variable refers to memory which does hold JSON data.
We could then transfer that data to a server written in an entirely different programming language, and as long as it has a JSON parser, it could parse it, and convert it to whatever object type makes sense to that server.

Are javascript objects and json data equivalent?

I'm learning javascript and just noticed that the syntax we use to define objects is the same as the json format. So I'm wondering if they are simply equivalent. Being more precise, does it mean that any javascript object (including its variables and functions) can be translated into json format and the same way around?
JSON is (like it's name "JavaScript Object Notation" indicates) a subset* of the JavaScript syntax, i.e. (nearly) every* JSON is valid JavaScript but not the other way round.
Functions, for example, have no equivalent representation in JSON and therefore, cannot be translated into JSON.
Since the main purpose for JSON is serialization, it doesn't provide representation of statements either.
* There is one exception: more or less all Unicode characters can be written literally in JSON but they must be written using escape sequences in JavaScript. See this blog post for more information. So not every valid JSON is valid JavaScript.
JSON data has only data specified in key-value pairs; where as js objects contain both data and functions enlisted in key-value pairs.
Think of JSON as a string representation of your javascript object. - String being the key word here.
Primarily used for easy transport over HTTP .It is a method created by Douglas Crockford to enable a friendly Javascript data transfer format similar to XML , RSS, et all.
JSON is generally parsed by server and client back into a Javascript object for use.

JSON to JavaScript object #text property

I am currently developing a JavaScript add-on which receives JSON from an API. So far, so good I retrieve the JSON and then use eval() to convert this JSON to a JavaScript object. This is where the problems start.
My JSON contains a '#text'-property. I evaluated the JavaScript object and found it also has this '#text'-property, but I can not call the property since variables with hash-tags are not accepted.
I know two possible solutions (use eval() to convert to an Array or remove the hast-tag), but I would prefer calling the property. Any ideas? Thanks.
You can reference object properties with square brackets:
var obj = {'#foo': 'bar'};
obj['#foo']; // 'bar'
Indeed, obj.#foo is invalid (i.e. will raise a syntax error), but the above method is fine.
Also, don't use eval unless you have to. Despite being a slower solution, it's less safe, especially considering there are usually so many native JSON methods, and most JSON libraries will introduce the functionality only if the native methods don't exist.
Don't use eval, especially for this. You a json parser, modern browsers already have them.
var myObj = JSON.parse(returnFromServer);
console.log(myObj.firstProperty); // etc
Here's a CDN link for json2 http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js
Do stuff before eval like replacing hash sign with something else.

Categories