# JSON Parser Examples

## Example 1: Parse Configuration File

```moonbit
fn load_config() {
  let config_json = "{\"host\": \"localhost\", \"port\": 8080, \"debug\": true}"
  let config = parse(config_json)
  
  match config {
    Object(obj) => {
      let host = obj.get("host").unwrap().as_string().unwrap()
      let port = obj.get("port").unwrap().as_number().unwrap()
      let debug = obj.get("debug").unwrap().as_bool().unwrap()
      
      println("Server: \{host}:\{port.to_int()}")
      println("Debug mode: \{debug}")
    }
    _ => ()
  }
}
```

## Example 2: Build and Serialize JSON

```moonbit
fn create_user_json() {
  let user : JsonValue = Object({
    "id": Number(123.0),
    "username": String("alice"),
    "email": String("alice@example.com"),
    "verified": Bool(true),
    "roles": Array([String("user"), String("admin")]),
  })
  
  let json_str = stringify(user)
  println(json_str)
}
```

## Example 3: Pretty Print JSON

```moonbit
fn format_json() {
  let data : JsonValue = Object({
    "name": String("Product"),
    "price": Number(99.99),
    "tags": Array([String("electronics"), String("gadget")]),
    "metadata": Object({
      "sku": String("ABC123"),
      "stock": Number(50.0),
    }),
  })
  
  let pretty = stringify_pretty(data, 2)
  println(pretty)
  // Output:
  // {
  //   "name": "Product",
  //   "price": 99.99,
  //   "tags": [
  //     "electronics",
  //     "gadget"
  //   ],
  //   "metadata": {
  //     "sku": "ABC123",
  //     "stock": 50
  //   }
  // }
}
```

## Example 4: Parse Array and Iterate

```moonbit
fn process_array() {
  let json = "[{\"name\": \"Alice\", \"score\": 95}, {\"name\": \"Bob\", \"score\": 87}]"
  let result = parse(json)
  
  match result {
    Array(items) => {
      for item in items {
        match item {
          Object(obj) => {
            let name = obj.get("name").unwrap().as_string().unwrap()
            let score = obj.get("score").unwrap().as_number().unwrap()
            println("\{name}: \{score}")
          }
          _ => ()
        }
      }
    }
    _ => ()
  }
}
```

## Example 5: Error Handling

```moonbit
fn safe_parse() {
  let inputs = [
    "{\"valid\": true}",
    "[1, 2, 3,]",  // Trailing comma
    "{\"key\": }",  // Missing value
    "invalid",
  ]
  
  for input in inputs {
    match try? parse(input) {
      Ok(value) => println("✓ Parsed: \{value}")
      Err(JsonError::TrailingComma(pos)) => {
        println("✗ Trailing comma at \{pos.line}:\{pos.column}")
      }
      Err(JsonError::UnexpectedChar(pos, ch)) => {
        println("✗ Unexpected '\{ch}' at \{pos.line}:\{pos.column}")
      }
      Err(err) => println("✗ Error: \{err}")
    }
  }
}
```

## Example 6: Round-Trip Conversion

```moonbit
fn round_trip_test() {
  let original = "{\"name\":\"test\",\"values\":[1,2,3]}"
  
  // Parse
  let parsed = parse(original)
  
  // Modify
  match parsed {
    Object(obj) => {
      obj["count"] = Number(3.0)
      obj["active"] = Bool(true)
    }
    _ => ()
  }
  
  // Stringify
  let modified = stringify(parsed)
  println("Modified: \{modified}")
  
  // Parse again
  let reparsed = parse(modified)
  println("Reparsed: \{reparsed}")
}
```

## Example 7: API Response Handling

```moonbit
fn handle_api_response() {
  let response_json = "{\"status\": \"success\", \"data\": {\"id\": 1, \"name\": \"Item\"}, \"message\": null}"
  let response = parse(response_json)
  
  match response {
    Object(obj) => {
      // Check status
      match obj.get("status") {
        Some(String("success")) => {
          // Process data
          match obj.get("data") {
            Some(Object(data)) => {
              println("ID: \{data.get("id")}")
              println("Name: \{data.get("name")}")
            }
            _ => ()
          }
        }
        Some(String("error")) => {
          println("Error occurred")
        }
        _ => ()
      }
      
      // Check message (might be null)
      match obj.get("message") {
        Some(Null) => println("No message")
        Some(String(msg)) => println("Message: \{msg}")
        _ => ()
      }
    }
    _ => ()
  }
}
```

## Example 8: Build Nested Structures

```moonbit
fn build_complex_json() {
  let address : JsonValue = Object({
    "street": String("123 Main St"),
    "city": String("Springfield"),
    "zip": String("12345"),
  })
  
  let contact : JsonValue = Object({
    "email": String("john@example.com"),
    "phone": String("555-0100"),
  })
  
  let user : JsonValue = Object({
    "id": Number(1001.0),
    "name": String("John Doe"),
    "age": Number(30.0),
    "address": address,
    "contact": contact,
    "interests": Array([
      String("reading"),
      String("coding"),
      String("gaming"),
    ]),
  })
  
  let json = stringify_pretty(user, 2)
  println(json)
}
```

## Example 9: Filter and Transform

```moonbit
fn filter_users() {
  let json = "[{\"name\":\"Alice\",\"age\":25},{\"name\":\"Bob\",\"age\":35},{\"name\":\"Carol\",\"age\":28}]"
  let result = parse(json)
  
  match result {
    Array(users) => {
      let adults : Array[JsonValue] = []
      
      for user in users {
        match user {
          Object(obj) => {
            match obj.get("age") {
              Some(Number(age)) if age >= 30.0 => adults.push(user)
              _ => ()
            }
          }
          _ => ()
        }
      }
      
      let filtered : JsonValue = Array(adults)
      println("Adults: \{stringify(filtered)}")
    }
    _ => ()
  }
}
```

## Example 10: Validate JSON Schema

```moonbit
fn validate_user_json(json: JsonValue) -> Bool {
  match json {
    Object(obj) => {
      // Check required fields
      let has_id = match obj.get("id") {
        Some(Number(_)) => true
        _ => false
      }
      
      let has_name = match obj.get("name") {
        Some(String(s)) => s.length() > 0
        _ => false
      }
      
      let has_email = match obj.get("email") {
        Some(String(s)) => s.contains("@")
        _ => false
      }
      
      has_id && has_name && has_email
    }
    _ => false
  }
}
```

## Real-World Use Cases

### 1. Configuration Files
Parse JSON config files for application settings.

### 2. API Communication
Parse HTTP API responses and serialize requests.

### 3. Data Storage
Store and retrieve structured data in JSON format.

### 4. Logging
Serialize application logs to JSON for structured logging.

### 5. Message Passing
Exchange data between components using JSON.

## Tips

1. **Always handle parse errors** - JSON can be malformed
2. **Use pattern matching** - Safely extract values from JsonValue
3. **Type annotations** - Add `: JsonValue` when constructing values
4. **Pretty print for debugging** - Use `stringify_pretty()` for readable output
5. **Round-trip testing** - Parse and stringify to verify correctness
