Answer the question
In order to leave comments, you need to log in
How to parse JavaScript Object (not valid JSON) in Golang?
Valid JSON first:
v1 := `{
"middle" : {
"src": "pictures/product/middle/14906_middle.jpg",
"place" : "#preview-img",
"title": "343880-090-slantsy-nike-benassi-just-do-it"
}
}`
v2 := `{
middle : {
src: 'pictures/product/middle/14906_middle.jpg',
place : '#preview-img',
title: '343880-090-slantsy-nike-benassi-just-do-it'
}
}`
error: invalid character 'm' looking for beginning of object key string
Answer the question
In order to leave comments, you need to log in
In js, you can convert an object to a valid json string
PS I don't understand why you can't pass a string instead of an object.
I have not yet compared these two options in terms of performance, but in future tasks I will prefer to use the first option.
On stackoverflow, it was advised to look at the https://godoc.org/launchpad.net/rjson#Unmarshal library , but it did not have support for values in single quotes.
As a result, I forked and added support for single quotes.
package main
import (
"fmt"
"github.com/mantyr/rjson"
)
func main() {
data := []byte(`{
middle : {
src: "pictures/product/123.jpg",
place : '#preview-img', // Added support for JavaScript object parsing
title: "title"
}
}`)
var v struct {
Middle struct {
Src string
Place string
Title string
}
}
err := rjson.Unmarshal(data, &v)
fmt.Println(v) // print {{pictures/product/123.jpg #preview-img title}}
fmt.Println(err) // print <nil>
}
package main
import (
"testing"
"github.com/robertkrimen/otto"
)
func BenchmarkVMGet(b *testing.B) {
vm := otto.New()
b.ResetTimer()
for i := 0; i < b.N; i++ {
st := `
{
middle : {
src: 'pictures/product/middle/14906_middle.jpg',
place : '#preview-img',
title: '343880-090-slantsy-nike-benassi-just-do-it'
}
}
`
vm.Run(`
obj = `+st+`
src = obj.middle.src;
`)
src, err := vm.Get("src") // <-----
_ = src
_ = err
}
}
# go test -bench=".*" ottotest
testing: warning: no tests to run
PASS
BenchmarkVMGet 30000 58103 ns/op
ok ottotest 2.367s
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question