I am a newbie to JSON & hence I am not sure what $.toJSON(params) means.
Please explain what this does.
It could be this jQuery plugin
var myObj = {};
myObj.propA = "a";
myObj.propB = "b";
myObj.propC = "c";
var jsonString = $.toJSON(myObj); // same as jQuery.toJSON(myObj)
// output: '{ "propA" : "a", "propB" : "b", "propC" : "c" }'
See: http://www.json.org/js.html
A JSON stringifier goes in the opposite direction, converting JavaScript data structures into JSON text. JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier.
var myJSONText = JSON.stringify(myObject, replacer);
If the stringify method sees an object that contains a toJSON method, it calls that method, and stringifies the value returned. This allows an object to determine its own JSON representation.
The stringifier method can take an optional array of strings. These strings are used to select the properties that will be included in the JSON text.
The stringifier method can take an optional replacer function. It will be called after the toJSON method (if there is one) on each of the values in the structure. It will be passed each key and value as parameters, and this will be bound to object holding the key. The value returned will be stringified.
So if you have a $.toJSON() method, it could be a badly implemented function to "stringify", or it could be a method that returns the "JSON Representation" of $
It passes the variable params as an argument to the method named toJSON attached to the object stored in the (unhelpfully named) variable $.
Based on the name, it probably converts the contents of the params variable to a String formatted according to the JSON specification.
Related
The question speaks for itself. JSON isn't a type. You have the function JSON.stringify(object). My opinion is that the resulting String from this function is JSON, not the object which is stringified. And if that is true JSON would be a String ?
JSON (JavaScript Object Notation) is a way to format object data as a string. You are correct in saying JSON is not a type. JSON.stringify(object) takes an object and returns a string. The string will contain the data of the object, but in a human-readable form.
So JSON is the string of an object.
JSON(JavaScript Object Notation) is a file-format that uses human-readable text.
In the following snippet, you can see that I created a JavaScript object (object) then I used JSON.stringify(object) to get the JSON version (string). typeof is used to show you the type of the element next to it.
typeof object will give you the type of object
You can also notice that there are some changes. For example, properties names are wrapped with double quotes " ", the values are wrapped with double quotes instead of simple,...
const object = {
propertyA : "This is my value A",
propertyB : [1,2,3],
propertyC : {test: 'Nice'}
};
console.log(typeof object);
console.log(JSON.stringify(object));
console.log(typeof JSON.stringify(object));
JSON is a Objects Notation (serialised), but JSON has specifice characteristics that it can be converted into/from specific syntax of String (for usage into different languages/platforms or for data transfer into different systems).
In javaScript :
to convert syntactically_correct_string to JSON we use JSON.parse(inputStringHere),
and to convert a JSON into String we use JSON.stringify(inputJSONobject).
if you need to read or clone all of a model’s data attributes, use its
toJSON() method. This method returns a copy of the attributes as an
object (not a JSON string despite its name). (When JSON.stringify() is
passed an object with a toJSON() method, it stringifies the return
value of toJSON() instead of the original object. The examples in the
previous section took advantage of this feature when they called
JSON.stringify() to log model instances.)
http://addyosmani.github.io/backbone-fundamentals/#backbone-basics
Can anyone tell me the difference between both these ways of representing an object in JSON notation. I am just confused whether these to achieve the same or there is a difference.
From the fine manual:
toJSON behavior
If an object being stringified has a property named toJSON whose value is a function, then the toJSON method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON method when called will be serialized.
This is why Backbone uses the toJSON method for serialization and given a model instance called m, you can say things like:
var string = JSON.stringify(m);
and get just the attributes out of m rather than a bunch of noise that your server won't care about.
That said, the main difference is that toJSON produces a value (a number, boolean, object, ...) that gets converted to a JSON string whereas JSON.stringify always produces a string.
The default Backbone toJSON is simply this (for models):
return _.clone(this.attributes);
so m.toJSON() gives you a shallow copy of the model's attributes. If there are arrays or objects as attribute values then you will end unexpected reference sharing. Note that Backbone.Model#clone also suffers from this problem.
If you want to safely clone a model's data then you could send it through JSON.stringify and then JSON.parse to get a deep copy:
var data = JSON.parse(JSON.stringify(model_instance));
var cloned_model = new M(data);
where model_instance is your instance of the Backbone model M.
JSON.stringify() - Any valid JSON representation value can be stringified.
The JSON.stringify(..) utility will automatically omit undefined, function, and symbol values when it comes across them. If such a value is found in an array, that value is replaced by null (so that the array position information isn't altered). If found as a property of an object, that property will simply be excluded.
JSON stringification has the special behavior that if an object value has a toJSON() method defined, this method will be called first to get a value to use for serialization.
toJSON() - to a valid JSON value suitable for stringification.
One example, JSON.stringify() an object with circular reference in it, an error will be thrown. toJSON() can fix it as following.
var o = { };
var a = {
b: 32,
c: o
};
// circular reference
o.d = a;
// JSON.stringify( a ); // an error caused by circular reference
// define toJSON method
a.toJSON = function() {
return { b: this.b };
};
JSON.stringify( a ); // "{"b":32}"
I'm also reading Addy Osmani's Developing backbone.js application, and I have the same question. I figured out by trying his example (the todo list) in the console.
var Todo = Backbone.Model.extend({
defaults:{
title:"",
completed:false
}
});
var todo1 = new Todo();
console.log(todo1.toJSON())
//The console shows
//Object {title: "finish your assignment", completed: false}
console.log(JSON.stringify(todo1))
//The console shows
//{"title":"finish your assignment","completed":false}
In both the cases I get in output the content of the object:
alert(JSON.stringify(obj));
or
alert(obj.toString());
so... what's the difference? what are the advantages or disadvantages of each one?
Are there practical examples to show the difference?
Unless you have a custom object with custom .toString method returning JSON.stringify of that object, there is no obj that would give obj.toString() == JSON.stringify(obj).
When obj is an array like [1,2,3] then .toString() gives:
"1,2,3"
And JSON.stringify:
"[1,2,3]"
These are close but not quite the same, the JSON serialized one has no ambiguity with commas and directly runs as Javascript or can be parsed as JSON.
See:
["1,",2,3].toString();
//"1,,2,3" ... so you can't just split by comma and get original array
//it is in fact impossible to restore the original array from this result
JSON.stringify(["1,",2,3])
//'["1,",2,3]'
//original array can be restored exactly
for an object say
obj = { a: 'a', '1': 1 }
obj.toString() gives
"[object Object]"
JSON.stringify(obj) gives
"{"1":1,"a":"a"}"
For .toString(), a default value is returned when the argument type is an object. JSON.stringify on the other hand returns JSON text, which can be converted back into a JSON object by using JSON.parse
As you might have noticed, while you tried (hopefully), calling .toString() which any object inherits (*) from Object.prototype.toString(), returns [object Object].
Thats how its defined internally, returning the internal [Class] name from an object. Of course, other objects can override this method (remember, its just originally defined on the prototype chain) and return pretty much anything.
JSON.stringify() on the other hand, is a method of the JSON object, which kind of serializes an object structure into a string version. Hence, Javascript Object Notation, it will describe an object with all nested structures in pure ascii string.
(*) exception: objects created with Object.create(null);
You can use the replacer and space parameter in JSON.stringify, passing the replacer argument as a function you can modify the object and space parameter helps you to give extra space before every key value pair.
const replacer = (key, value) => {
// Filtering out properties
if (typeof value === 'number') {
return 1;
}
return value;
},
foo = {
country: 'India',
state: 'Gujarat',
district: 45,
cm: 'car',
am: 7
},
result = JSON.stringify(foo, replacer);
console.log(result) // {"country":"India","state":"Gujarat","district":1,"cm":"car","am":1}
Space argument -
const obj = { a : 1, b:2};
const obj_str = JSON.stringify(obj, null, ' ');// '\t' gives one tab
console.log(obj_str)
For more details you can visit this link.
I have a method that receives something and it needs to determine the type of the received value. I can use the typeof thing to perform regular comparisons like if it is a number or a string. But how can I do this for JSON objects? Comparing them with JSON brings up the error:
Uncaught TypeError: Expecting a function in instanceof check, but got #< Object>
So I guess that comparing a JSON object type with JSON is not the way?
The original code is like:
check = (what) ->
if what instanceof JSON
alert "Yooo"
check({compare: "me"})
The type will be object, not JSON. To see what you're working with, you can check if it has the properties you're looking for. Check the length, or if it has specific keys.
Here's a pretty good informational page on working with JSON. JSON in JavaScript
JSON stands for JavaScript Object notation and is simply a name for how object literals are written in JavaScript it is not a type.
var a = {"foo":"My foo","bar" : 4};
var b = {"foo":"My foo","bar" : 0};
var c = {"foo":"My c foo","barella" : -1};
var d = '{"baz":"My baz","bar" : 4}';
a,b,c and d are all objects the first three of type object the fourth of type string. You could from a type theoretic point of view say that the first two have the same type. If you did eval("var e =" + d) then the string would be in d would be evaluated and since d is an object serialized to JSON the result would be a valid object that would be assigned to e.
in other words JSON is no type it's part of the JavaScript grammar, the result of evaluating JSON is an object and the type of that object will vary depending on the object literal. using typeof on such an object will yield "object" (regards less of the type theoretic type of the object).
If you wish to test and object against a specific type you would therefor have to test it for all the expected properties and methods
class JSON
constructor: (#data) ->
get: (key) ->
#data[key]
set: (key, value) ->
#data[key] = value
a = new JSON "foo":"My foo", "bar" : 4
a.get('foo')
a.data.foo
a.data['foo']
console.log(a instanceof JSON)
:D You really shouldn't be doing this though, at least not to create a JSON type. But it's possible that you can create your own wrapper for pretty much anything. Combining this with the Object.defineProperty to setup getters and setters based on #data, you could do some powerful stuff. It doesn't have method_missing methods, but you can achieve similar results with Object.defineProperty
First type of return string, second, there is no such thing as Type JSON in type of possible return values. see the this page for detail
in your case you will receive "object".
Is it possible to perform complex queries over a JSON object? I am open to JavaScript or jQuery solutions, the easier the better. I'm envisioning some kind of functional programming language similar to LINQ or SQL.
I Prefer no other third party libraries or add-ons.
UPDATE
From the looks of early answers, an add-on is going to be necessary. In that case, I prefer an add-on that requires no installation process. Something that deploys with the software publish (like jQuery) is fine (e.g. sets of *.js files).
Check out: Is there a query language for JSON?
From that thread:
JaQL(Wiki)
JsonPath.
Json Query
By the time you're interacting with it, it's not a "JSON object," it's a JavaScript object. ("JSON objects" only exist in terms of the data notation.) JavaScript itself doesn't have any advanced functional programming constructs, so you'd need third party libraries for that sort of thing. JavaScript pretty much just has property accessors, an operator for "does this object have a property with this name?" (in, hasOwnProperty), and as of the 5th edition (not yet widely supported), some handy array-specific features like forEach, every, map, filter, and the like.
Use JSON.stringify and a replacer callback to achieve this:
function replacer(match, offset, fullstring)
{
return replacer.str;
}
replacer.str = "\u0022filterValues\u0022:[\u0022hi\u0022,\u0022bye\u0022]"; /* Use DOM node value */
var foo = JSON.stringify({
"Region": {
"filterField": "kw_Region",
"filterValues": [
"aa",
"bb"
]
},
"ApplicationName": {
"filterField": "kw_ApplicationName",
"filterValues": [
"aa",
"bb"
]
},
"IssueType": {
"filterField": "kw_IssueType",
"filterValues": [
"aa",
"bb"
]
},
"Outage": {
"filterField": "kw_Outage",
"filterValues": [
"aa",
"bb"
]
},
"Priority": {
"filterField": "kw_Priority",
"filterValues": [
"aa",
"bb"
]
}
}).replace(/"filterValues[^\]]+./g, replacer)
Here is some documentation on the two JSON methods for serialization and transformation, stringify and parse:
JSON.parse(source, reviver)
This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted.
The reviver is ultimately called with the empty string and the topmost value to permit transformation of the topmost value. Be certain to handle this case properly, usually by returning the provided value, or JSON.parse will return undefined.
if (k === "") return v
JSON.stringify(value, replacer, space)
The stringify method produces a JSON text from a JavaScript value. If value is an object or array, the structure will be visited recursively to determine the serialization of each membr or element. The structure must not be cyclical.
When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the object holding the key.
You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization.
If the replacer parameter is an array, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified.
Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read.
If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces.
var alias = {"Clark":"","phone":""};
function kryptonite(key)
{
var replacement = {};
for(var cursor in this)
{
if(cursor in alias)
replacement[cursor] = this[cursor]
}
return replacement;
}
var contact = {
"Clark":"Kent",
"Kal El":"Superman",
"phone":"555-7777"
}
contact.toJSON = kryptonite;
var foo = JSON.stringify(contact) // "{"Clark":"Kent","phone":"555-7777"}"
References
ECMAScript Wiki:JSON Support
MDN:JSON.parse Examples
MDN:JSON.stringify toJSON behavior
MSDN:toJSON Method
Opera:JSON.parse
hmm... YQL does this sort of thing, but that would be a third party.
you could filter an array with the jQuery $.grep(array,filterfn) method
var newArr = $.grep(oldArr,function(elInArray,index){
return elInArray.key === somevalue;
});
and you can of course use a regexp in there if you wish, or use more complex conditions, such as checking multiple keys, keys within keys, arrays within keys, etc.