Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save thanhtungka91/15116009645f516c5a4da095673c368c to your computer and use it in GitHub Desktop.
Save thanhtungka91/15116009645f516c5a4da095673c368c to your computer and use it in GitHub Desktop.
convert query to string json
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"regexp"
)
func main() {
// Hard-coded file name
fileName := "input.txt"
// Read the content from the file
input, err := ioutil.ReadFile(fileName)
if err != nil {
fmt.Fprintf(os.Stderr, "Error reading file %s: %v\n", fileName, err)
os.Exit(1)
}
s := string(input)
// Step 1: Replace Ruby hash rockets (=>) with JSON colons (:)
reRocket := regexp.MustCompile(`=>`)
s = reRocket.ReplaceAllString(s, ":")
// Step 2: Quote unquoted keys.
// Updated regex: Match keys starting with a digit, letter, or underscore.
reKeys := regexp.MustCompile(`(?m)(^|\{|,)\s*([0-9A-Za-z_]\w*)\s*:`)
s = reKeys.ReplaceAllString(s, `$1 "$2":`)
// Optionally, if needed, replace single quotes with double quotes:
// reSingle := regexp.MustCompile(`'`)
// s = reSingle.ReplaceAllString(s, `"`)
// Step 3: Validate the JSON by unmarshaling it
var result interface{}
if err := json.Unmarshal([]byte(s), &result); err != nil {
fmt.Fprintf(os.Stderr, "Error parsing JSON: %v\nTransformed output:\n%s\n", err, s)
os.Exit(1)
}
// Step 4: Pretty-print the JSON
output, err := json.MarshalIndent(result, "", " ")
if err != nil {
fmt.Fprintf(os.Stderr, "Error generating JSON: %v\n", err)
os.Exit(1)
}
fmt.Println(string(output))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment