├── .github ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── DOCUMENTATION.md ├── images │ ├── carbon.png │ └── jsonc.png └── workflows │ └── go.yml ├── .gitignore ├── LICENSE ├── README.md ├── go.mod ├── jsonc.go ├── jsonc_test.go └── translator.go /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at muhammadmuzzammil.cs@gmail.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to jsonc 2 | :tada: First off, thanks for taking the time to contribute! :tada: 3 | 4 | Contributions are welcome but kindly follow the Code of Conduct and guidelines. 5 | Please don't make Pull Requests for typographical errors, grammatical mistakes, "sane way" of doing it, etc. 6 | Open an issue for it. Thanks! 7 | 8 | Please don't make contributions like fixing a comment, fixing spelling mistakes or changing code/format which doesn't provide more functionality to the project itself. Kindly open an issue for it. 9 | If there is a big issue, first open an issue to discuss it and then after discussion, refer that issue in the pull request's description to link them. 10 | 11 | ## Code Of Conduct 12 | We need you to strictly follow our code of conduct. Help us make a better community. 13 | ### What is Code of conduct? 14 | A code of conduct defines standards for how to engage in a community. It signals an inclusive environment that respects all contributions. It also outlines procedures for addressing problems between members of your project's community. 15 | ### Read our Code of conduct 16 | You can read our code of conduct [here](./CODE_OF_CONDUCT.md) 17 | -------------------------------------------------------------------------------- /.github/DOCUMENTATION.md: -------------------------------------------------------------------------------- 1 | # Documentation for JSONC 2 | 3 | ## ToJSON() 4 | 5 | Converts JSONC to JSON equivalent by removing all comments. 6 | 7 | ```go 8 | func ToJSON(b []byte) []byte 9 | ``` 10 | 11 | Example: 12 | 13 | ```go 14 | func main() { 15 | j := []byte(`{"foo": /*comment*/ "bar"}`) 16 | jc := jsonc.ToJSON(j) 17 | fmt.Println(string(jc)) // {"foo":"bar"} 18 | } 19 | ``` 20 | 21 | ## ReadFromFile() 22 | 23 | Reads jsonc file and returns JSONC and JSON encodings. 24 | 25 | ```go 26 | func ReadFromFile(filename string) ([]byte, []byte, error) 27 | ``` 28 | 29 | Example: 30 | 31 | ```go 32 | func main() { 33 | jc, j, err := jsonc.ReadFromFile("data.jsonc") 34 | if err != nil { 35 | log.Fatal(err) 36 | } 37 | // jc and j contains JSONC and JSON, respectively. 38 | } 39 | ``` 40 | 41 | ## Unmarshal() 42 | 43 | Parses the JSONC-encoded data and stores the result in the value pointed to by passed interface. Equivalent of calling `json.Unmarshal(jsonc.ToJSON(data), v)`. 44 | 45 | ```go 46 | func Unmarshal(data []byte, v interface{}) error 47 | ``` 48 | 49 | Example: 50 | 51 | ```go 52 | func main(){ 53 | type UnmarshalTest struct { 54 | Foo string `json:"foo"` 55 | True bool `json:"true"` 56 | Num int `json:"number"` 57 | Object struct { 58 | Test string `json:"test"` 59 | } `json:"object"` 60 | Array []int `json:"array"` 61 | } 62 | 63 | un := UnmarshalTest{} 64 | jc, _, _ := jsonc.ReadFromFile("data.jsonc") 65 | if err := jsonc.Unmarshal(jc, &un); err != nil { 66 | log.Fatal("Unable to unmarshal.", err) 67 | } 68 | fmt.Println(string(jc)) 69 | fmt.Printf("%+v", un) 70 | } 71 | ``` 72 | 73 | Output: 74 | 75 | ```sh 76 | $ go run .\main.go 77 | { 78 | /* This is an example 79 | for block comment. */ 80 | "foo": "bar foo", // Comments can 81 | "true": false, // Improve readability. 82 | "number": 42, // Number will always be 42. 83 | /* Comments are ignored while 84 | generating JSON from JSONC. */ 85 | "object": { 86 | "test": "done" 87 | }, 88 | "array": [1, 2, 3] 89 | } 90 | 91 | {Foo:bar foo True:false Num:42 Object:{Test:done} Array:[1 2 3]} 92 | ``` 93 | 94 | ## Valid() 95 | 96 | Reports whether data is a valid JSONC encoding or not. 97 | 98 | ```go 99 | func Valid(data []byte) bool 100 | ``` 101 | 102 | Example: 103 | 104 | ```go 105 | func main() { 106 | jc1 := []byte(`{"foo":/*comment*/"bar"}`) 107 | jc2 := []byte(`{"foo":/*comment/"bar"}`) 108 | fmt.Println(jsonc.Valid(jc1)) // true 109 | fmt.Println(jsonc.Valid(jc2)) // false 110 | } 111 | ``` 112 | -------------------------------------------------------------------------------- /.github/images/carbon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/muhammadmuzzammil1998/jsonc/9d456f027e71480e4581c07f39519caffc4c60d9/.github/images/carbon.png -------------------------------------------------------------------------------- /.github/images/jsonc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/muhammadmuzzammil1998/jsonc/9d456f027e71480e4581c07f39519caffc4c60d9/.github/images/jsonc.png -------------------------------------------------------------------------------- /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: Go 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | 11 | build: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v2 15 | 16 | - name: Set up Go 17 | uses: actions/setup-go@v2 18 | with: 19 | go-version: 1.17 20 | 21 | - name: Build 22 | run: go build -v ./... 23 | 24 | - name: Test 25 | run: go test -v ./... 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, build with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Muhammad Muzzammil 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 2 | 3 | ![jsonc](.github/images/jsonc.png) 4 | 5 |

6 | JSON with comments for Go!
7 | GitHub Actions 8 |

9 | 10 | JSONC is a superset of JSON which supports comments. JSON formatted files are readable to humans but the lack of comments decreases readability. With JSONC, you can use block (`/* */`) and single line (`//` of `#`) comments to describe the functionality. Microsoft VS Code also uses this format in their configuration files like `settings.json`, `keybindings.json`, `launch.json`, etc. 11 | 12 | ![jsonc](.github/images/carbon.png) 13 | 14 | ## What this package offers 15 | 16 | **JSONC for Go** offers ability to convert and unmarshal JSONC to pure JSON. It also provides functionality to read JSONC file from disk and return JSONC and corresponding JSON encoding to operate on. However, it only provides a one way conversion. That is, you can not generate JSONC from JSON. Read [documentation](.github/DOCUMENTATION.md) for detailed examples. 17 | 18 | ## Usage 19 | 20 | ### `go get` it 21 | 22 | Run `go get` command to install the package. 23 | 24 | ```sh 25 | $ go get muzzammil.xyz/jsonc 26 | ``` 27 | 28 | ### Import jsonc 29 | 30 | Import `muzzammil.xyz/jsonc` to your source file. 31 | 32 | ```go 33 | package main 34 | 35 | import ( 36 | "fmt" 37 | 38 | "muzzammil.xyz/jsonc" 39 | ) 40 | ``` 41 | 42 | ### Test it 43 | 44 | Now test it! 45 | 46 | ```go 47 | func main() { 48 | j := []byte(`{"foo": /*comment*/ "bar"}`) 49 | jc := jsonc.ToJSON(j) // Calling jsonc.ToJSON() to convert JSONC to JSON 50 | if jsonc.Valid(jc) { 51 | fmt.Println(string(jc)) 52 | } else { 53 | fmt.Println("Invalid JSONC") 54 | } 55 | } 56 | ``` 57 | 58 | ```sh 59 | $ go run app.go 60 | {"foo":"bar"} 61 | ``` 62 | 63 | ## Contributions 64 | 65 | Contributions are welcome but kindly follow the Code of Conduct and guidelines. Please don't make Pull Requests for typographical errors, grammatical mistakes, "sane way" of doing it, etc. Open an issue for it. Thanks! 66 | 67 | ### Contributors 68 | 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/muhammadmuzzammil1998/jsonc/v1 2 | 3 | go 1.17 4 | -------------------------------------------------------------------------------- /jsonc.go: -------------------------------------------------------------------------------- 1 | // MIT License 2 | 3 | // Copyright (c) 2019 Muhammad Muzzammil 4 | 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | 12 | // The above copyright notice and this permission notice shall be included in all 13 | // copies or substantial portions of the Software. 14 | 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | // SOFTWARE. 22 | 23 | package jsonc 24 | 25 | import ( 26 | "encoding/json" 27 | "io/ioutil" 28 | ) 29 | 30 | // ToJSON returns JSON equivalent of JSON with comments 31 | func ToJSON(b []byte) []byte { 32 | return translate(b) 33 | } 34 | 35 | // ReadFromFile reads jsonc file and returns JSONC and JSON encodings 36 | func ReadFromFile(filename string) ([]byte, []byte, error) { 37 | data, err := ioutil.ReadFile(filename) 38 | if err != nil { 39 | return nil, nil, err 40 | } 41 | jc := data 42 | j := translate(jc) 43 | return jc, j, nil 44 | } 45 | 46 | // Unmarshal parses the JSONC-encoded data and stores the result in the value pointed to by v. 47 | // Equivalent of calling `json.Unmarshal(jsonc.ToJSON(data), v)` 48 | func Unmarshal(data []byte, v interface{}) error { 49 | j := translate(data) 50 | return json.Unmarshal(j, v) 51 | } 52 | 53 | // Valid reports whether data is a valid JSONC encoding or not 54 | func Valid(data []byte) bool { 55 | j := translate(data) 56 | return json.Valid(j) 57 | } 58 | -------------------------------------------------------------------------------- /jsonc_test.go: -------------------------------------------------------------------------------- 1 | package jsonc 2 | 3 | import ( 4 | "encoding/json" 5 | "io/ioutil" 6 | "os" 7 | "reflect" 8 | "testing" 9 | ) 10 | 11 | func b(s string) []byte { return []byte(s) } 12 | func s(b []byte) string { return string(b) } 13 | 14 | type testsStruct struct { 15 | validBlock []byte 16 | validSingle []byte 17 | invalidBlock []byte 18 | invalidSingle []byte 19 | validHash []byte 20 | invalidHash []byte 21 | } 22 | 23 | var jsonTest, jsoncTest testsStruct 24 | 25 | func init() { 26 | jsonTest = testsStruct{ 27 | validBlock: b(`{"foo":"bar foo","true":false,"number":42,"object":{"test":"done"},"array":[1,2,3],"url":"https://github.com","escape":"\"wo//rking"}`), 28 | invalidBlock: b(`{"foo":`), 29 | } 30 | jsoncTest = testsStruct{ 31 | validBlock: b(`{"foo": /** this is a bloc/k comm\"ent */ "bar foo", "true": /* true */ false, "number": 42, "object": { "test": "done" }, "array" : [1, 2, 3], "url" : "https://github.com", "escape":"\"wo//rking" }`), 32 | invalidBlock: b(`{"foo": /* this is a block comment "bar foo", "true": false, "number": 42, "object": { "test": "done" }, "array" : [1, 2, 3], "url" : "https://github.com", "escape":"\"wo//rking }`), 33 | validSingle: b("{\"foo\": // this is a \"single **/line comm\\\"ent\n\"bar foo\", \"true\": false, \"number\": 42, \"object\": { \"test\": \"done\" }, \"array\" : [1, 2, 3], \"url\" : \"https://github.com\", \"escape\":\"\\\"wo//rking\" }"), 34 | invalidSingle: b(`{"foo": // this is a single line comment "bar foo", "true": false, "number": 42, "object": { "test": "done" }, "array" : [1, 2, 3], "url" : "https://github.com", "escape":"\"wo//rking" }`), 35 | validHash: b("{\"foo\": # this is a single line comm\\\"ent\n\"bar foo\", \"true\": false, \"number\": 42, \"object\": { \"test\": \"done\" }, \"array\" : [1, 2, 3], \"url\" : \"https://github.com\", \"escape\":\"\\\"wo//rking\" }"), 36 | invalidHash: b(`{"foo": # this is a single line comment "bar foo", "true": false, "number": 42, "object": { "test": "done" }, "array" : [1, 2, 3], "url" : "https://github.com", "escape":"\"wo//rking" }`), 37 | } 38 | } 39 | 40 | func TestToJSON(t *testing.T) { 41 | tests := []struct { 42 | name string 43 | arg []byte 44 | want []byte 45 | wantErr bool 46 | }{ 47 | { 48 | name: "Test for valid block comment.", 49 | arg: jsoncTest.validBlock, 50 | want: jsonTest.validBlock, 51 | }, { 52 | name: "Test for invalid block comment.", 53 | arg: jsoncTest.invalidBlock, 54 | want: jsonTest.invalidBlock, 55 | wantErr: true, 56 | }, { 57 | name: "Test for valid single line comment.", 58 | arg: jsoncTest.validSingle, 59 | want: jsonTest.validBlock, 60 | }, { 61 | name: "Test for invalid single line comment.", 62 | arg: jsoncTest.invalidSingle, 63 | want: jsonTest.invalidBlock, 64 | wantErr: true, 65 | }, { 66 | name: "Test for valid single line comment started with hash.", 67 | arg: jsoncTest.validHash, 68 | want: jsonTest.validBlock, 69 | }, { 70 | name: "Test for invalid single line comment started with hash.", 71 | arg: jsoncTest.invalidHash, 72 | want: jsonTest.invalidBlock, 73 | wantErr: true, 74 | }, 75 | } 76 | for _, tt := range tests { 77 | t.Run(tt.name, func(t *testing.T) { 78 | got := ToJSON(tt.arg) 79 | if !reflect.DeepEqual(got, tt.want) { 80 | t.Errorf("ToJSON() = %v, want %v", s(got), s(tt.want)) 81 | } 82 | if !json.Valid(got) && !tt.wantErr { 83 | t.Errorf("ToJSON() = %v isn't valid.", s(got)) 84 | } 85 | }) 86 | } 87 | } 88 | 89 | func TestUnmarshal(t *testing.T) { 90 | type UnmarshalTest struct { 91 | Foo string `json:"foo"` 92 | True bool `json:"true"` 93 | Num int `json:"number"` 94 | Object struct { 95 | Test string `json:"test"` 96 | } `json:"object"` 97 | Array []int `json:"array"` 98 | URL string `json:"url"` 99 | Escape string `json:"escape"` 100 | } 101 | 102 | t.Run("Testing Unmarshal()", func(t *testing.T) { 103 | un := UnmarshalTest{} 104 | if err := Unmarshal(jsoncTest.validBlock, &un); err != nil { 105 | t.Errorf("Unmarshal() error = %v", err) 106 | } 107 | mr, err := json.Marshal(un) 108 | if err != nil { 109 | t.Errorf("Unmarshal() unable to marshal Unmarshal(). Error = %v, got = %v, want = %v", err, s(mr), s(jsonTest.validBlock)) 110 | } 111 | if !reflect.DeepEqual(mr, jsonTest.validBlock) { 112 | t.Errorf("Unmarshal() didn't work correctly. Got = %v, want = %v", s(mr), s(jsonTest.validBlock)) 113 | } 114 | }) 115 | } 116 | 117 | func TestReadFromFile(t *testing.T) { 118 | tmp, err := ioutil.TempFile("", "ReadFromFileTest") 119 | if err != nil { 120 | t.Skip("Unable to create temp file.", err) 121 | } 122 | defer os.Remove(tmp.Name()) 123 | 124 | if _, err := tmp.Write(jsoncTest.validBlock); err != nil { 125 | t.Skip("Unable to write to file.", err) 126 | } 127 | 128 | defer func() { 129 | if err := tmp.Close(); err != nil { 130 | t.Log("Unable to close the file.", err) 131 | } 132 | }() 133 | 134 | tests := []struct { 135 | name string 136 | filename string 137 | want []byte 138 | want1 []byte 139 | wantErr bool 140 | }{ 141 | { 142 | name: "Valid use of ReadFromFile()", 143 | filename: tmp.Name(), 144 | want: jsoncTest.validBlock, 145 | want1: jsonTest.validBlock, 146 | wantErr: false, 147 | }, 148 | { 149 | name: "Invalid use of ReadFromFile()", 150 | filename: "NonExistentFile", 151 | wantErr: true, 152 | }, 153 | } 154 | for _, tt := range tests { 155 | t.Run(tt.name, func(t *testing.T) { 156 | got, got1, err := ReadFromFile(tt.filename) 157 | if (err != nil) != tt.wantErr { 158 | t.Errorf("ReadFromFile() error = %v, wantErr %v", err, tt.wantErr) 159 | return 160 | } 161 | if !reflect.DeepEqual(got, tt.want) { 162 | t.Errorf("ReadFromFile() got = %v, want %v", got, tt.want) 163 | } 164 | if !reflect.DeepEqual(got1, tt.want1) { 165 | t.Errorf("ReadFromFile() got1 = %v, want %v", got1, tt.want1) 166 | } 167 | }) 168 | } 169 | } 170 | 171 | func TestValid(t *testing.T) { 172 | tests := []struct { 173 | name string 174 | data []byte 175 | want bool 176 | }{ 177 | { 178 | name: "Valid test", 179 | data: b(`{"foo":/*comment*/"bar"}`), 180 | want: true, 181 | }, 182 | { 183 | name: "Invalid test", 184 | data: b(`{"foo"://comment without ending`), 185 | want: false, 186 | }, 187 | } 188 | for _, tt := range tests { 189 | t.Run(tt.name, func(t *testing.T) { 190 | if got := Valid(tt.data); got != tt.want { 191 | t.Errorf("Valid() = %v, want %v", got, tt.want) 192 | } 193 | }) 194 | } 195 | } 196 | 197 | func BenchmarkTranslate(b *testing.B) { 198 | for n := 0; n < b.N; n++ { 199 | translate(jsoncTest.validSingle) 200 | translate(jsoncTest.validBlock) 201 | translate(jsoncTest.validHash) 202 | } 203 | } 204 | 205 | func BenchmarkValid(b *testing.B) { 206 | for n := 0; n < b.N; n++ { 207 | Valid(jsoncTest.validSingle) 208 | Valid(jsoncTest.validBlock) 209 | Valid(jsoncTest.validHash) 210 | } 211 | } 212 | -------------------------------------------------------------------------------- /translator.go: -------------------------------------------------------------------------------- 1 | // MIT License 2 | 3 | // Copyright (c) 2019 Muhammad Muzzammil 4 | 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | 12 | // The above copyright notice and this permission notice shall be included in all 13 | // copies or substantial portions of the Software. 14 | 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | // SOFTWARE. 22 | 23 | package jsonc 24 | 25 | const ( 26 | ESCAPE = 92 27 | QUOTE = 34 28 | SPACE = 32 29 | TAB = 9 30 | NEWLINE = 10 31 | ASTERISK = 42 32 | SLASH = 47 33 | HASH = 35 34 | ) 35 | 36 | func translate(s []byte) []byte { 37 | var ( 38 | i int 39 | quote bool 40 | escaped bool 41 | ) 42 | j := make([]byte, len(s)) 43 | comment := &commentData{} 44 | for _, ch := range s { 45 | if ch == ESCAPE || escaped { 46 | if !comment.startted { 47 | j[i] = ch 48 | i++ 49 | } 50 | escaped = !escaped 51 | continue 52 | } 53 | if ch == QUOTE && !comment.startted { 54 | quote = !quote 55 | } 56 | if (ch == SPACE || ch == TAB) && !quote { 57 | continue 58 | } 59 | if ch == NEWLINE { 60 | if comment.isSingleLined { 61 | comment.stop() 62 | } 63 | continue 64 | } 65 | if quote && !comment.startted { 66 | j[i] = ch 67 | i++ 68 | continue 69 | } 70 | if comment.startted { 71 | if ch == ASTERISK && !comment.isSingleLined { 72 | comment.canEnd = true 73 | continue 74 | } 75 | if comment.canEnd && ch == SLASH && !comment.isSingleLined { 76 | comment.stop() 77 | continue 78 | } 79 | comment.canEnd = false 80 | continue 81 | } 82 | if comment.canStart && (ch == ASTERISK || ch == SLASH) { 83 | comment.start(ch) 84 | continue 85 | } 86 | if ch == SLASH { 87 | comment.canStart = true 88 | continue 89 | } 90 | if ch == HASH { 91 | comment.start(ch) 92 | continue 93 | } 94 | j[i] = ch 95 | i++ 96 | } 97 | return j[:i] 98 | } 99 | 100 | type commentData struct { 101 | canStart bool 102 | canEnd bool 103 | startted bool 104 | isSingleLined bool 105 | endLine int 106 | } 107 | 108 | func (c *commentData) stop() { 109 | c.startted = false 110 | c.canStart = false 111 | } 112 | 113 | func (c *commentData) start(ch byte) { 114 | c.startted = true 115 | c.isSingleLined = ch == SLASH || ch == HASH 116 | } 117 | --------------------------------------------------------------------------------