I posted this in discord a while ago 
(<https://discord.com/channels/371759389889003530/371759389889003532/1070078955010400286>)

Maybe you find it useful:
    
    
    import std/[macros, json, tables, sequtils]
    
    
    
    func typeStringFromJsonKind(k: JsonNodeKind): string =
      case k:
      of JBool: "bool"
      of JInt: "int"
      of JFloat: "float"
      of JString: "string"
      else:
        error("Unsupported json kind: " & $k)
        ""
    
    macro typefromjs(js : static string, typ: untyped) : untyped =
      result = typ
      let props = parseJson(js).getFields().pairs.toSeq()
      let params = nnkRecList.newTree(props.mapIt(nnkIdentDefs.newTree(ident 
$it[0], ident typeStringFromJsonKind(it[1].kind), newEmptyNode())))
      result[^1] = nnkObjectTy.newTree(newEmptyNode(), newEmptyNode(), params)
    
    
    type MyJsonType {.typefromjs: """{"someTestField": 3.14, 
"someTestFieldString": "hello"}""" .}
    
    proc main() =
      let test = parseJson("""{"someTestField": 1.14, "someTestFieldString": 
"adios"}""")
                .to(MyJsonType)
      echo $test
    
    main()
    
    
    Run

Reply via email to