Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
# jsonc - https://pkg.go.dev/github.com/fpatron/jsonc
# jsonc

[![Go CI](https://github.com/fpatron/jsonc/actions/workflows/go.yml/badge.svg)](https://github.com/fpatron/jsonc/actions/workflows/go.yml)
[![Go Doc](https://img.shields.io/badge/godoc-reference-blue.svg)](http://godoc.org/github.com/fpatron/jsonc)

`jsonc` is an extension of the JSON data format that allows single and multi line comments and provides accurate parsing errors.
`jsonc` is an extension of the JSON data format that allows single and multi line comments.

## Instalation
To install `jsonc`, use `go get`:
Expand All @@ -13,7 +14,6 @@ To install `jsonc`, use `go get`:
## Features

- **Comment Support**: Easily parse JSON files with single-line and multi-line comments.
- **Accurate Errors**: Errors while parsing will match original commented JSON.
- **Simple API**: Uses a familiar API similar to the standard `encoding/json` package.

## Usage
Expand Down
26 changes: 26 additions & 0 deletions jsonc.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,32 @@ func stripComments(data []byte) []byte {
)

state := OUTSIDE
hasComment := false
scanLoop:
for i := 0; i < len(data); i++ {
switch state {
case OUTSIDE:
if data[i] == '/' && i+1 < len(data) && (data[i+1] == '/' || data[i+1] == '*') {
hasComment = true
break scanLoop
}
if data[i] == '"' {
state = IN_STRING
}
case IN_STRING:
if data[i] == '\\' && i+1 < len(data) {
i++
} else if data[i] == '"' {
state = OUTSIDE
}
}
}

if !hasComment {
return data
}

state = OUTSIDE
result := make([]byte, 0, len(data))

for i := 0; i < len(data); i++ {
Expand Down
26 changes: 26 additions & 0 deletions v2/jsonc.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,32 @@ func stripComments(data []byte) []byte {
)

state := OUTSIDE
hasComment := false
scanLoop:
for i := 0; i < len(data); i++ {
switch state {
case OUTSIDE:
if data[i] == '/' && i+1 < len(data) && (data[i+1] == '/' || data[i+1] == '*') {
hasComment = true
break scanLoop
}
if data[i] == '"' {
state = IN_STRING
}
case IN_STRING:
if data[i] == '\\' && i+1 < len(data) {
i++
} else if data[i] == '"' {
state = OUTSIDE
}
}
}

if !hasComment {
return data
}

state = OUTSIDE
result := make([]byte, 0, len(data))

for i := 0; i < len(data); i++ {
Expand Down