Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
14 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions website/docs/how-to-guides/_category_.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
{
"label": "How-To Guide",
"label": "How - To Guides",
"position": 3,
"link": {
"type": "generated-index"
"type": "generated-index",
"description": "5 minutes to practice the most important api-ts concepts."
}
}
69 changes: 69 additions & 0 deletions website/docs/how-to-guides/parsing-json-strings.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# How To Parse JSON Strings

## Basic JSON String Parsing
```typescript
import * as t from 'io-ts'

// Define the expected structure
const UserCodec = t.type({
name: t.string,
age: t.number,
email: t.string
})

// Parse JSON string and validate structure
const jsonString = '{"name": "Alice", "age": 30, "email": "alice@example.com"}'

// First parse the JSON string
const parsed = JSON.parse(jsonString)

// Then validate the parsed data
const result = UserCodec.decode(parsed)
// Success: { name: "Alice", age: 30, email: "alice@example.com" }

// Example with invalid data
const invalidJson = '{"name": "Bob", "age": "30"}' // age should be number
const invalidParsed = JSON.parse(invalidJson)
const invalidResult = UserCodec.decode(invalidParsed)
// Error: Invalid value "30" supplied to : { name: string, age: number, email: string }/age: number
```

## Nested JSON String Parsing

```typescript
import * as t from 'io-ts'
import { DateFromISOString } from 'io-ts-types'

// Define a codec that handles nested structures and dates
const EventCodec = t.type({
id: t.string,
timestamp: DateFromISOString,
data: t.type({
title: t.string,
participants: t.array(t.type({
id: t.string,
role: t.union([
t.literal('organizer'),
t.literal('attendee')
])
}))
})
})

// Example JSON string with nested structure
const jsonString = `{
"id": "evt_123",
"timestamp": "2024-01-15T10:30:00Z",
"data": {
"title": "Team Meeting",
"participants": [
{"id": "user_1", "role": "organizer"},
{"id": "user_2", "role": "attendee"}
]
}
}`

// Parse and validate in one step
const result = EventCodec.decode(JSON.parse(jsonString))
// Success: Parsed with proper Date object and validated structure
```
Loading