Skip to content
Open
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
15 changes: 11 additions & 4 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -712,12 +712,10 @@ func WriteToBuffer(buffer []byte, str string) int {
}

/*

Del - Receives existing data structure, path to delete.

Returns:
`data` - return modified data

*/
func Delete(data []byte, keys ...string) []byte {
lk := len(keys)
Expand Down Expand Up @@ -798,13 +796,11 @@ func Delete(data []byte, keys ...string) []byte {
}

/*

Set - Receives existing data structure, path to set, and data to set at that key.

Returns:
`value` - modified byte array
`err` - On any parsing error

*/
func Set(data []byte, setValue []byte, keys ...string) (value []byte, err error) {
// ensure keys are set
Expand Down Expand Up @@ -1103,6 +1099,7 @@ func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType Va
return nil
}

var lastCommaIdx = -1
// Loop pre-condition: data[offset] points to what should be either the next entry's key, or the closing brace (if it's anything else, the JSON is malformed)
for offset < len(data) {
// Step 1: find the next key
Expand All @@ -1113,6 +1110,11 @@ func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType Va
case '"':
offset++ // accept as string and skip opening quote
case '}':
// Detect if the previous token was a comma. For rxample: { "": 12,}
if lastCommaIdx != -1 && lastCommaIdx+1 == offset {

return MalformedObjectError
}
return nil // we found the end of the object; stop and return success
default:
return MalformedObjectError
Expand Down Expand Up @@ -1164,6 +1166,7 @@ func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType Va
case '}':
return nil // Stop if we hit the close brace
case ',':
lastCommaIdx = offset
offset++ // Ignore the comma
default:
return MalformedObjectError
Expand All @@ -1174,6 +1177,10 @@ func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType Va
if off := nextToken(data[offset:]); off == -1 {
return MalformedArrayError
} else {
if off > 0 {
// advance lastCommaIdx to skip to the next token
lastCommaIdx += off - 1
}
offset += off
}
}
Expand Down
5 changes: 5 additions & 0 deletions parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1630,6 +1630,11 @@ var objectEachTests = []ObjectEachTest{
json: `{"key": "value",, "key2": "value2"}`,
isErr: true,
},
{
desc: "bad value (extra comma)",
json: `{"":[],}`,
isErr: true,
},
}

func TestObjectEach(t *testing.T) {
Expand Down