Standard Library
JSON

JSON Module

The json module provides funcs for parsing and stringifying JSON data.

funcs

json.stringify()

Convert a Flowa value to JSON string:

let obj = {
    "name": "Alice",
    "age": 30,
    "active": true,
    "tags": ["developer", "admin"]
};
 
let json_str = json.stringify(obj);
print(json_str);
// {"name":"Alice","age":30,"active":true,"tags":["developer","admin"]}

json.parse()

Parse JSON string to Flowa value:

let json_text = "{\"x\": 10, \"y\": 20}";
let data = json.parse(json_text);
 
print(data["x"]);  // 10
print(data["y"]);  // 20

Examples

API Response Handling

// Simulated API response
let api_response = "{\"users\": [{\"id\": 1, \"name\": \"Alice\"}, {\"id\": 2, \"name\": \"Bob\"}], \"total\": 2}";
 
let data = json.parse(api_response);
let users = data["users"];
 
let i = 0;
while (i < len(users)) {
    print("User: " + users[i]["name"]);
    i = i + 1;
}

Configuration Management

// Save config
let config = {
    "database": {
        "host": "localhost",
        "port": 5432,
        "name": "myapp"
    },
    "api_key": "secret123",
    "debug": true
};
 
let config_json = json.stringify(config);
fs.writeFile("config.json", config_json);
 
// Load config
let loaded_json = fs.readFile("config.json");
let loaded_config = json.parse(loaded_json);
print(loaded_config["database"]["host"]);

Data Export

let users = [];
users = push(users, {"id": 1, "name": "Alice", "email": "alice@example.com"});
users = push(users, {"id": 2, "name": "Bob", "email": "bob@example.com"});
 
let export_data = {
    "export_date": "2024-12-12",
    "users": users,
    "count": len(users)
};
 
fs.writeFile("export.json", json.stringify(export_data));

Best Practices

  • Always use quoted strings for hash keys
  • Handle parse errors by checking for null
  • Validate JSON structure after parsing
  • Use for data interchange between systems

Next Steps