Skip to content

Instantly share code, notes, and snippets.

@GrimTheReaper
Last active December 5, 2016 21:45
Show Gist options
  • Save GrimTheReaper/4f95b4229461a892eba15071e9ec25a2 to your computer and use it in GitHub Desktop.
Save GrimTheReaper/4f95b4229461a892eba15071e9ec25a2 to your computer and use it in GitHub Desktop.
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
Copy link
Author

GrimTheReaper commented Dec 5, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment