How to parse JavaScript Object (not valid JSON) in Golang?

Question:

First, a valid JSON:

v1 := `{
        "middle" : {
        "src": "pictures/product/middle/14906_middle.jpg",
        "place" : "#preview-img",
        "title": "343880-090-slantsy-nike-benassi-just-do-it"
        }
    }`

Now valid JavaScript Object, but not valid JSON:

v2 := `{
        middle : {
        src: 'pictures/product/middle/14906_middle.jpg',
        place : '#preview-img',
        title: '343880-090-slantsy-nike-benassi-just-do-it'
        }
    }`

Tell me how to parse the second option? The usual encoding.json.Unmarshal () complains about being invalid.

error: invalid character 'm' looking for beginning of object key string

Maybe there is some kind of library in which this nuance can be configured?

Update:

You can start the VM https://github.com/robertkrimen/otto and pass it a little augmented text to get the desired field from it.

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

However, there are downsides:

  • an arbitrary piece of text can fly in and execute it thoughtlessly incorrectly (remember eval in php )
  • slow enough
  • very large library used – bad dependency

Pros:

  • still fast enough
  • you can not stop the VM, but push there through Run, but if pushing endlessly, the question remains – will it die once or not – without a good knowledge of the internals of the library, this cannot be said in advance

I'm still looking for other options, purely for the task of parsing the object and not performing unnecessary operations.

Answer:

There is a library for this at launchpad.net/rjson . If the key matches the regex

[a-zA-Z][a-zA-Z0-9\-_]*

Note that in JavaScript the $ symbol can be used – but not here.

However, launchpad.net/rjson does not support single quotes in values. To fix this, a fork was made which can be taken here: github.com/mantyr/rjson

Scroll to Top