JSON
&
Javascript
objects
json
- Stands for JavaScript Object Notation
- Used & supported in many languages besides JS
- Is better than XML (my opinion (but not really))
- Used to move data between the client & server
Object Format
{
"title" : "Manager",
"first name" : "John",
"last name" : "Doe",
"office location" : "Seattle, WA"
}
Array Format
[
"cat",
"dog",
"aardvark",
"hedgehog"
]
array + object example
[
{
"type" : "dog",
"breed" : "border collie",
"name" : "Maybe"
},
{
"type" : "aardvark",
"breed" : "awesomeness",
"name" : "Spike"
}
]
Json key concepts
- Comma separated (both Arrays and Objects)
- Double quotes...
- ... except for numbers & booleans...
- ... but always with properties.
- Use JSONLint all the time.
the json object
JSON.parse()
Converts a string of JSON into a workable, JS object.
JSON.parse('{ "aprop" : "thing" }');
// > { aprop : 'thing' }
JSON.stringify()
Converts a JS object into a string of JSON.
JSON.stringify({ 'anotherProp' : 'person' });
// > "{"anotherProp" : "person" }"
foreach loops
Similar to Java/C++/C# foreach loops.
Syntax:
for(var key in obj) {
//do stuff
}
*obj is an existing object
*key becomes the local variable of the current property being looked at in the object
Accessing a property inside the above loop:
other string things
Concatenating Strings:
var fullName = 'John ' + 'Doe';
Multi-line Strings (uses concatenation):
var bunchOfStuff = 'I don't know ' +
'what to write, I just need ' +
'to fill up some lines.';
Escaping quotes:
var excapeQts = 'I got single \'s in my';
var dblQts = "double \"s.";
var mxdQts = 'this is a dbl " in';
var mxdQts2 = "some single 's.";
make some functions
Examples
Cool JS thing for the day
Javascript game about programming Javascript.
Give it a try!