Win an Ipad
  Developer   Tutorials   Beginners’ tutorial ...   Working with JSON
Lesson 7

Working with JSON

Usefull links

Value Objects

JavaScript object is basically a set of pair key-value, it is an associative arrays. Here is example of simple object.
var valObj = {
     prop1: "string value",
     prop2: 1234, // integer value
     prop3: [1, 2, "c", "d"], // array
     // etc
     // for: "reserved keyword" // ERROR!
} valObj.debugShow();

Console:

Class Object: [object Class]
     Properties:
          prop3: 1,2,c,d
          prop2: 1234
          prop1: "string value"

It's very easy to convert a object to a string or to a file (to serialize it). It's done by printf method of String or Stream class. To format value object uses %V or %v (value):

var strRep1 = String.printf("%V", valObj);
console << strRep1 << "\n";


var fileRep1 = Stream.openFile("data://val.mso", "w+8");
fileRep1.printf("%V", valObj);
fileRep1.close();


This is an output of serialisation:

{
     prop3:[1,2,"c","d"],
     prop2:1234,
     prop1:"string value"
     }

JSON Objects

According to ECMAScript it's required to use quoted keys. To save value object to a valid JSON, you have to use %J or %j (JSON) instead of %v:

var strRep2 = String.printf("%J", valObj);
console << strRep2 << "\n";

Output:

{
     "prop3":[1,2,"c","d"],
     "prop2":1234,
     "prop1":"string value"
     }

Parsing value and JSON objects

Parsing serialized value object is done by global parseData function:

var parsedObj = parseData("{prop3:[1,2,\"c\",\"d\"],prop2:1234,prop1:\"string value\"}");
for (var p in parsedObj)
    console << "parsedObj[" << p << "] = " << parsedObj[p] << "\n";

Output:

parsedObj[prop1] = string value
parsedObj[prop2] = 1234
parsedObj[prop3] = 1,2,c,d
parsedObj.prop3 = 1,2,c,d

The same function is used to parse serialized JSON object:

var parsedJSON = parseData("{\"prop3\":[1,2,\"c\",\"d\"],\"prop2\":1234,\"prop1\":\"string value\"}");
for (var p in parsedJSON)
    console << "parsedJSON[" << p << "] = " << parsedJSON[p] << "\n";
console << "parsedJSON.prop3 = " << parsedJSON.prop3 << "\n";
console << "parsedJSON[\"prop3\"] = " << parsedJSON["prop3"] << "\n";

Output:

parsedJSON[prop1] = string value
parsedJSON[prop2] = 1234
parsedJSON[prop3] = 1,2,c,d
parsedJSON.prop3 = undefined
parsedJSON["prop3"] = 1,2,c,d

 Movable scrolling ba ...   Working with JSON   Creating a high scor ... 
Tutorial details and chapters
Technology:
iOS, Android
Difficulty:
Beginner
Completion:
15 min
Beginners’ tutorial series chapters