DEV Community

udomsak
udomsak

Posted on

4 1

It's possible to pare JSON via DSL or dynamic input template in Golang

Example

Input

{
   "name" : "udomsak",
   "dataForm" : { 
     "attribute1": "myname is"
     "gender" : "male",
     "location": "Mars"
}

Parser Language

This parser language is Dynamic and does not need to compile in Struct in Golang. that mean can get from database or file use as parser.

ParserGet:
  - name
  - dataForm.gender 
  - dataForm.location

Example request

ProjectA:

http://api.example.com/parser-rule/parser1
  - parser1 load from parser rule file :  "parser1.rule.conf"

ProjectB:
http://api.example.com/parser-rule/parser2
  - parser1 load from parser rule file :  "parser2.rule.conf"

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (2)

Collapse
 
vorsprung profile image
vorsprung

OK, what you haven't explained is that in Go, JSON parsing can occur directly into structs

With your example, this is complicated with the need for a struct inside a struct

package main

import (
    "encoding/json"
    "fmt"
)

type DataForm struct {
    Attribute1 string `json:"attribute1"`
    Gender     string `json:"gender"`
    Location   string `json:"location"`
}

type Example struct {
    Name      string   `json:"name"`
    DataFormd DataForm `json:"dataForm"`
}

var testdata = `{
  "name": "udomsak",
  "dataForm": {
    "attribute1": "myname is",
    "gender": "male",
    "location": "Mars"
  }
}`

func main() {
    var data Example

    json.Unmarshal([]byte(testdata), &data)

    fmt.Printf("Hello, %v", data.DataFormd.Attribute1)
}

The problem is that JSON can contain all kinds of fields and nested data and Go requires the schema to be declared ahead of time with struct declarations

However it's possible to load arbitrary JSON into Go anyway

Just load it into an empty interface

var data interface{}

json.Unmarshal([]byte(testdata), &data)

but then accessing fields in the data becomes a major pita. To achieve the same as above...

fmt.Printf("Hello, %v", (data.(map[string]interface{}))["dataForm"].(map[string]interface{})["attribute1"])
Collapse
 
udomsak profile image
udomsak

@vorsprung thank you for answer me and sorry for very lately reply. I'm so busy. But for this problem look like i must use custom parser to work with this case. ( goyacc ).

my intend is you json as form ( json form-schema ) and anyone can create they form as need. that mean in server-side they need implement custom parser to get attribute they need. :)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay