This project has moved. For the latest updates, please go here.

JavaScript Object

Create object using JSON literal in ReoScript:
var obj = { name: 'apple', 
            color: 'red',
            amount: 3 };

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

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 instead of the eval. JSON.parse supported by ReoScript internal function(using ANTLR) that runs in very low level, more faster and safer:
var str = "{name:'apple', color:'red', amount:3}";
var obj = JSON.parse(str);

JSON.parse supports to use a handler lambda to process each values:
var str = "{name:'apple', color:'red', amount:3}";
var obj = JSON.parse(str, (key, value) => String(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);

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

You may also provide a handler lambda to format each values:
var obj = {name: 'apple', color: 'red', amount: 3};
var str = JSON.stringify(obj, (key, value) => (key == 'amount' ? String(value) : value));

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

ReoScript Extension

Convert .NET objects to JSON string

.NET class 'Fruit':
public class Fruit
{
   public string Name { get; set; }
   public string Color { get; set; }
   public int Amount { get; set; }
}

Create instance and add it into script:
Fruit apple = new Fruit() {
    Name = "apple",
    Color = "red",
    Amount = 5
};

srm["obj"] = apple;

Using JSON.stringify convert it into string:
var str = JSON.stringify(obj);

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

Last edited Dec 23, 2013 at 3:00 PM by unvell, version 4