A simple and efficient JSON parser written in Go that can parse JSON strings and files into Go data structures.
- Parses JSON strings and files
- Supports all standard JSON data types:
- Objects (maps)
- Arrays
- Strings
- Numbers
- Booleans
- Null
- Pretty printing of parsed JSON
- Error handling for invalid JSON
package main
import (
"encoding/json"
"fmt"
)
func main() {
// Parse a JSON string
jsonStr := `{"name": "John", "age": 30, "isStudent": false, "height": 1.75, "skills": ["JavaScript", "Python", "Go"]}`
parser := NewParser(jsonStr)
jsonObject, err := parser.Parse()
if err != nil {
fmt.Println("Error:", err)
return
}
// Access parsed data
name := jsonObject.(map[string]any)["name"].(string)
fmt.Println("Name:", name)
// Pretty print the parsed JSON
prettyJSON, err := json.MarshalIndent(jsonObject.(map[string]any), "", " ")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Pretty Print:", string(prettyJSON))
// Parse a JSON file
fileParser := NewParser(string(fileContent))
fileObject, err := fileParser.Parse()
if err != nil {
fmt.Println("Error:", err)
return
}
// ... work with fileObject
}The parser uses a recursive descent approach with the following components:
- Lexer: Tokenizes the input string into JSON tokens
- Parser: Converts tokens into Go data structures
Parse(): Main entry point for parsingparseObject(): Handles JSON objectsparseArray(): Handles JSON arraysparseValue(): Handles primitive values
The parser provides clear error messages for common JSON parsing issues:
- Unexpected end of file
- Invalid token types
- Missing commas
- Invalid object/array structure
main.go- Contains the main program entry point and example usagelexer.go- Implements the JSON lexer functionalitytoken.go- Defines token types and structures
The lexer recognizes the following token types:
STRING- JSON string valuesNUMBER- Numeric values (integers and floating-point)BOOLEAN- true/false valuesNULL- null valuesCOLON- Key-value separator (:)COMMA- Value separator (,)LEFT_BRACE- Object start ({)RIGHT_BRACE- Object end (})LEFT_BRACKET- Array start ([)RIGHT_BRACKET- Array end (])EOF- End of inputILLEGAL- Invalid tokens
- Go 1.x or later
To build and run the project:
go build
./jsonparserThis project is open source and available under the MIT License.