Created
March 7, 2025 11:00
-
-
Save thanhtungka91/15116009645f516c5a4da095673c368c to your computer and use it in GitHub Desktop.
convert query to string json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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