Skip to content

Instantly share code, notes, and snippets.

@GrimTheReaper GrimTheReaper/Preparse.go
Last active Dec 5, 2016

Embed
What would you like to do?
Preparsing JSON
// Example of how to preparse a JSON String.
// Useful if the json is massive and what you are looking for is on the top.
//
// Use:
// preParseString(JSONKey, JSONBody) => Value of JSONKey, or "" if not found.
//
func preParseString(key string, body []byte) string {
var buffer []byte
level := 0
qO := false // quoteOpen
eonf := false // end on next flush
escaped := false
for ii := 0; ii < len(body); ii++ {
switch body[ii] {
case '"':
if !escaped {
qO = !qO // Toggle.
// Flush.
if !qO {
if len(buffer) > 0 {
if eonf {
return string(buffer)
}
if string(buffer) == key {
eonf = true
}
buffer = make([]byte, 0) // Clear.
}
}
} else {
escaped = false
buffer = append(buffer, body[ii])
}
case '{':
if !qO {
level++
}else {
buffer = append(buffer, body[ii])
}
case '}':
if !qO {
level--
}else {
buffer = append(buffer, body[ii])
}
case '[', ':': // Level handling.
if qO {
buffer = append(buffer, body[ii])
}
// Ignore.
case ',', ']':
if eonf && !qO {
return ""
}
if qO {
buffer = append(buffer, body[ii])
}
case '\\':
if escaped {
buffer = append(buffer, body[ii])
}
escaped = !escaped // TODO make sure the next character is the one we are escaping.
default:
if escaped {
// Ignore?
escaped = false
} else if qO {
if level == 1 {
buffer = append(buffer, body[ii])
}
}
}
}
return "" // If it isn't found, reutrn nil.
}
@GrimTheReaper

This comment has been minimized.

Copy link
Owner Author

GrimTheReaper commented Dec 5, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.