Hi, I'm writing a JSON serialization test case for the `type Price = 
tuple[price: float, currency: string]` type, and have 2 issues:

  1. How to parse custom JSON format `"214.05 USD".parse_json.to(Price)`, 
currently it fails complaining JSON is invalid, although it would work if it 
were inside of some other JSON object, like `{ price: "214.05 USD" }`.
  2. Another strange error when equality `assert Price.init(214.05, 
"USD").to_json == "214.05 USD"` fails, although it seems that the `to_json` 
outputs the same string `"214.05 USD"`.



Code and the [playground](https://play.nim-lang.org/#ix=2KkV):
    
    
    import strformat, json, strutils
    
    type Price = tuple[price: float, currency: string]
    
    proc init*(_: typedesc[Price], raw: string): Price =
      let parts = raw.split(" ")
      assert parts.len == 2, fmt"invalid price '{raw}'"
      (parse_float(parts[0]), parts[1])
    
    proc init*(_: typedesc[Price], price: float, currency: string): Price =
      (price, currency)
    
    func `$`*(v: Price): string =
      fmt"{v.price} {v.currency}"
    
    func `%`*(s: Price): JsonNode =
      %($s)
    
    proc init_from_json*(dst: var Price, json: JsonNode, json_path: string) =
      dst = Price.init(json.get_str)
    
    proc to_s*[T](v: T): string = $v
    proc to_json*[T](v: T): string = (%v).pretty
    
    # Testing
    
    let price = Price.init(214.05, "USD")
    
    assert price.to_s    == "214.05 USD"
    assert price.to_json == "214.05 USD"                                  # 
Strange error N1
    
    assert "214.05 USD".parse_json.to(Price) == Price.init(214.05, "USD") # 
JSON parsing error N2
    
    
    Run

Reply via email to