Skip to content

Commit f1229bf

Browse files
author
David Hu
committed
Initial commit: Complete JSONPath implementation following RFC 9535
- Full RFC 9535 compliant implementation\n- Command line tool with color support\n- Go library with comprehensive documentation\n- Complete test coverage\n- Both English and Chinese documentation
0 parents  commit f1229bf

File tree

13 files changed

+1550
-0
lines changed

13 files changed

+1550
-0
lines changed

.cursorrules

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
2+
You are an expert AI programming assistant specializing in building APIs with Go, using the standard library's net/http package and the new ServeMux introduced in Go 1.22.
3+
4+
Always use the latest stable version of Go (1.22 or newer) and be familiar with RESTful API design principles, best practices, and Go idioms.
5+
6+
- Follow the user's requirements carefully & to the letter.
7+
- First think step-by-step - describe your plan for the API structure, endpoints, and data flow in pseudocode, written out in great detail.
8+
- Confirm the plan, then write code!
9+
- Write correct, up-to-date, bug-free, fully functional, secure, and efficient Go code for APIs.
10+
- Use the standard library's net/http package for API development:
11+
- Utilize the new ServeMux introduced in Go 1.22 for routing
12+
- Implement proper handling of different HTTP methods (GET, POST, PUT, DELETE, etc.)
13+
- Use method handlers with appropriate signatures (e.g., func(w http.ResponseWriter, r *http.Request))
14+
- Leverage new features like wildcard matching and regex support in routes
15+
- Implement proper error handling, including custom error types when beneficial.
16+
- Use appropriate status codes and format JSON responses correctly.
17+
- Implement input validation for API endpoints.
18+
- Utilize Go's built-in concurrency features when beneficial for API performance.
19+
- Follow RESTful API design principles and best practices.
20+
- Include necessary imports, package declarations, and any required setup code.
21+
- Implement proper logging using the standard library's log package or a simple custom logger.
22+
- Consider implementing middleware for cross-cutting concerns (e.g., logging, authentication).
23+
- Implement rate limiting and authentication/authorization when appropriate, using standard library features or simple custom implementations.
24+
- Leave NO todos, placeholders, or missing pieces in the API implementation.
25+
- Be concise in explanations, but provide brief comments for complex logic or Go-specific idioms.
26+
- If unsure about a best practice or implementation detail, say so instead of guessing.
27+
- Offer suggestions for testing the API endpoints using Go's testing package.
28+
29+
Always prioritize security, scalability, and maintainability in your API designs and implementations. Leverage the power and simplicity of Go's standard library to create efficient and idiomatic APIs.
30+

.gitignore

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Binaries for programs and plugins
2+
*.exe
3+
*.exe~
4+
*.dll
5+
*.so
6+
*.dylib
7+
jp
8+
9+
# Test binary, built with `go test -c`
10+
*.test
11+
12+
# Output of the go coverage tool, specifically when used with LiteIDE
13+
*.out
14+
15+
# Dependency directories (remove the comment below to include it)
16+
vendor/
17+
18+
# Go workspace file
19+
go.work
20+
21+
# IDE specific files
22+
.idea/
23+
.vscode/
24+
*.swp
25+
*.swo
26+
.DS_Store

README.md

Lines changed: 240 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,240 @@
1+
# Go JSONPath
2+
3+
[![Go Reference](https://pkg.go.dev/badge/github.com/davidhoo/jsonpath.svg)](https://pkg.go.dev/github.com/davidhoo/jsonpath)
4+
[![Go Report Card](https://goreportcard.com/badge/github.com/davidhoo/jsonpath)](https://goreportcard.com/report/github.com/davidhoo/jsonpath)
5+
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6+
7+
[中文文档](README_zh.md)
8+
9+
A complete Go implementation of JSONPath that fully complies with [RFC 9535](https://www.rfc-editor.org/rfc/rfc9535). Provides both a command-line tool and a Go library with support for all standard JSONPath features.
10+
11+
## Features
12+
13+
- Complete RFC 9535 Implementation
14+
- Root node access (`$`)
15+
- Child node access (`.key` or `['key']`)
16+
- Recursive descent (`..`)
17+
- Array indices (`[0]`, `[-1]`)
18+
- Array slices (`[start:end:step]`)
19+
- Array wildcards (`[*]`)
20+
- Multiple indices (`[1,2,3]`)
21+
- Filter expressions (`[?(@.price < 10)]`)
22+
- Command Line Tool (`jp`)
23+
- Colorized output for readability
24+
- File and stdin input support
25+
- Formatted and compact output options
26+
- User-friendly error messages
27+
- Go Library
28+
- Clean API design
29+
- Type-safe operations
30+
- Rich examples
31+
- Comprehensive documentation
32+
33+
## Installation
34+
35+
### Command Line Tool
36+
37+
```bash
38+
go install github.com/davidhoo/jsonpath/cmd/jp@latest
39+
```
40+
41+
Or build from source:
42+
43+
```bash
44+
git clone https://github.com/davidhoo/jsonpath.git
45+
cd jsonpath
46+
go build -o jp cmd/jp/main.go
47+
```
48+
49+
### Go Library
50+
51+
```bash
52+
go get github.com/davidhoo/jsonpath
53+
```
54+
55+
## Command Line Usage
56+
57+
### Basic Usage
58+
59+
```bash
60+
jp -p <jsonpath_expression> [-f <json_file>] [-c]
61+
```
62+
63+
Options:
64+
- `-p` JSONPath expression (required)
65+
- `-f` JSON file path (reads from stdin if not specified)
66+
- `-c` Compact output (no formatting)
67+
- `-h` Show help information
68+
- `-v` Show version information
69+
70+
### Examples
71+
72+
```bash
73+
# Read from file
74+
jp -f data.json -p '$.store.book[*].author'
75+
76+
# Read from stdin
77+
echo '{"name": "John"}' | jp -p '$.name'
78+
79+
# Compact output
80+
jp -f data.json -p '$.store.book[0]' -c
81+
```
82+
83+
## Go Library Usage
84+
85+
### Basic Usage
86+
87+
```go
88+
import "github.com/davidhoo/jsonpath"
89+
90+
// Compile JSONPath expression
91+
jp, err := jsonpath.Compile("$.store.book[*].author")
92+
if err != nil {
93+
log.Fatal(err)
94+
}
95+
96+
// Execute query
97+
result, err := jp.Execute(data)
98+
if err != nil {
99+
log.Fatal(err)
100+
}
101+
102+
// Handle result
103+
authors, ok := result.([]interface{})
104+
if !ok {
105+
log.Fatal("unexpected result type")
106+
}
107+
```
108+
109+
### Complete Example
110+
111+
```go
112+
package main
113+
114+
import (
115+
"encoding/json"
116+
"fmt"
117+
"log"
118+
"github.com/davidhoo/jsonpath"
119+
)
120+
121+
func main() {
122+
// JSON data
123+
data := `{
124+
"store": {
125+
"book": [
126+
{
127+
"category": "reference",
128+
"author": "Nigel Rees",
129+
"title": "Sayings of the Century",
130+
"price": 8.95
131+
},
132+
{
133+
"category": "fiction",
134+
"author": "Evelyn Waugh",
135+
"title": "Sword of Honour",
136+
"price": 12.99
137+
}
138+
]
139+
}
140+
}`
141+
142+
// Parse JSON
143+
var v interface{}
144+
if err := json.Unmarshal([]byte(data), &v); err != nil {
145+
log.Fatal(err)
146+
}
147+
148+
// Compile and execute JSONPath
149+
jp, err := jsonpath.Compile("$.store.book[?(@.price < 10)].title")
150+
if err != nil {
151+
log.Fatal(err)
152+
}
153+
154+
result, err := jp.Execute(v)
155+
if err != nil {
156+
log.Fatal(err)
157+
}
158+
159+
// Print result
160+
fmt.Printf("%v\n", result) // ["Sayings of the Century"]
161+
}
162+
```
163+
164+
### Common Query Examples
165+
166+
```go
167+
// Get all prices (recursive)
168+
"$..price"
169+
170+
// Get books within price range
171+
"$.store.book[?(@.price < 10)].title"
172+
173+
// Get all authors
174+
"$.store.book[*].author"
175+
176+
// Get first book
177+
"$.store.book[0]"
178+
179+
// Get last book
180+
"$.store.book[-1]"
181+
182+
// Get first two books
183+
"$.store.book[0:2]"
184+
185+
// Get all books with price > 10
186+
"$.store.book[?(@.price > 10)]"
187+
```
188+
189+
### Result Handling
190+
191+
Handle results according to their type using type assertions:
192+
193+
```go
194+
// Single value result
195+
if str, ok := result.(string); ok {
196+
// Handle string result
197+
}
198+
199+
// Array result
200+
if arr, ok := result.([]interface{}); ok {
201+
for _, item := range arr {
202+
// Handle each item
203+
}
204+
}
205+
206+
// Object result
207+
if obj, ok := result.(map[string]interface{}); ok {
208+
// Handle object
209+
}
210+
```
211+
212+
## Implementation Details
213+
214+
1. RFC 9535 Compliance
215+
- Support for all standard operators
216+
- Standard-compliant syntax parsing
217+
- Standard result formatting
218+
219+
2. Filter Support
220+
- Comparison operators: `<`, `>`, `<=`, `>=`, `==`, `!=`
221+
- Currently supports numeric comparisons
222+
- Future support for string comparisons and logical operators
223+
224+
3. Result Handling
225+
- Array operations return array results
226+
- Single value access returns original type
227+
- Type-safe result handling
228+
229+
4. Error Handling
230+
- Detailed error messages
231+
- Syntax error reporting
232+
- Runtime error handling
233+
234+
## Contributing
235+
236+
Issues and Pull Requests are welcome!
237+
238+
## License
239+
240+
MIT License

0 commit comments

Comments
 (0)