Golang : How to convert strange string to JSON with json.MarshalIndent
Problem:
Your database is spewing out a funny looking string that looks like this {"width";800;"height";450}
and you want to map that string into something like this
[
{
width: 800,
height: 450,
}
]
You've tried converting the string to byte and decode with json.Unmarshal without luck. Is there a way to convert the string?
Solution:
First, clean up the funny/strange
string into something sensible with strings.Replace()
function and then format it to JSON with json.MarshalIndent()
function. json.MarshalIndent()
is to pretty-print the JSON output to multiple lines instead of lumping everything into a single line.
Here you go!
package main
import (
"encoding/json"
"fmt"
"os"
"strings"
)
func main() {
strFromDB := `{"width";800;"height";450}`
// deal with ;
// change ; to : after "
dealtWith := strings.Replace(strFromDB, "\";", "\":", -1)
fmt.Println("Converted to : ", dealtWith)
// trim and split
noCurlyBraces := strings.Replace(dealtWith, "{", "", -1)
noCurlyBraces = strings.Replace(noCurlyBraces, "}", "", -1)
// turn to slice
strSliceWithQuote := strings.Split(noCurlyBraces, ";")
fmt.Println("Slice : ", strSliceWithQuote)
jsonWithQuote, err := json.MarshalIndent(strSliceWithQuote, "", " ")
if err != nil {
fmt.Println(err)
os.Exit(-1)
}
fmt.Println("JSON : \n",string(jsonWithQuote))
}
Output :
Converted to : {"width":800;"height":450}
Slice : ["width":800 "height":450]
JSON :
[
"\"width\":800",
"\"height\":450"
]
See also : Golang : How to convert JSON string to map and slice
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+25k Golang : Convert long hexadecimal with strconv.ParseUint example
+17.4k Convert JSON to CSV in Golang
+5.6k Golang : Markov chains to predict probability of next state example
+10.3k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+14.2k Golang : Send email with attachment(RFC2822) using Gmail API example
+42.7k Golang : Convert []byte to image
+13.8k Golang : concatenate(combine) strings
+13.1k Golang : Verify token from Google Authenticator App
+8k Prevent Write failed: Broken pipe problem during ssh session with screen command
+6.2k PHP : Proper way to get UTF-8 character or string length
+27.1k Golang : Convert CSV data to JSON format and save to file
+18.6k Golang : How to make function callback or pass value from function as parameter?