Skip to content
Jing Lu edited this page Jun 14, 2013 · 20 revisions

JavaScript Object

Create object using JSON literal in ReoScript:

var obj = { name: 'apple', 
            color: 'red',
            amount: 3 };

Access properties of obj:

console.log(obj.name + ": " + obj.color);

The text below will be printed out:

apple: red

JSON

Convert string to object

Convert string to object using eval function:

var str = "{name:'apple', color:'red', amount:3}";
var obj = eval("(" + str + ")");

Or use JSON.parse to parse JSON string. JSON.parse supported by ReoScript internal function(using ANTLR) runs in very low level, it is more faster and safer than eval:

var str = "{name:'apple', color:'red', amount:3}";
var obj = JSON.parse(str);

JSON.parse supports to use a handler lambda to process every values:

var str = "{name:'apple', color:'red', amount:3}";
var obj = JSON.parse(str, (key, value) => value);

The obj is:

{
  name: 'apple', 
  color: 'red',
  amount: 3
}

Convert object to string

Convert object to string by JSON.stringify method:

var obj = {name: 'apple', color: 'red', amount: 3};
var str = JSON.stringify(obj);

The str will be:

{name:"apple",color:"red",amount:3}

You may also provide the handler lambda to process what kind of result you want to be converted from a value:

var obj = {name: 'apple', color: 'red', amount: 3};
var str = JSON.stringify(obj, (key, value) => (key == 'amount' ? String(value) : value));

The str will be:

{name:"apple",color:"red",amount:"3"}

ReoScript Extension

Convert .Net object to JSON string

'Fruit' is a .Net class defined in C#:

public class Fruit
{
  public string Name { get; set; }
  public string Color { get; set; }
  public int Amount { get; set; }
}

Create an instance and add into script context:

Fruit apple = new Fruit() {
  Name = "apple",
  Color = "red",
  Amount = 5
};

srm["obj"] = apple;

Now convert it into JSON string:

var str = JSON.stringify(obj);

The str will be:

{Name:"apple",Color:"red",Amount:5}