mtth / avsc

Avro for JavaScript :zap:
MIT License
1.27k stars 147 forks source link

Avro union - remove type information in resulting json #434

Closed HIngelhag closed 1 year ago

HIngelhag commented 1 year ago

I wanna remove the type information from the resulting JSON I get when using fromBuffer.

My implementation look like this:

import {Type} from "avsc"

const buffer = .....

const type = Type.forSchema({
  fields: [
    { default: null, name: "id", type: ["null", "string"] },
  ],
  name: "schemaName",
  namespace: "exampleNamespace",
  type: "record",
})

const result = type.fromBuffer(buffer)
console.log(result.toString())

What I get is this:

{
  id: {
    string: "123456789"
  }
}

.. but I want it to look like this:

{
  id: "123456789"
}

Is that feasible without writing my own parser?

mtth commented 1 year ago

Hi @HIngelhag. You can directly use the record in this case:

console.log(result); //  {id: "123456789"}
console.log(JSON.stringify(result));  "{\"id\":\"123456789\"}"

This works because "optional" unions can always be unwrapped. Depending on your union's included types, the above record might also need to use a wrapped representation.

Finally, toString returns the record's JSON-encoded representation, which always includes type information. You can set the omitRecordMethods option to true when creating the type if you'd prefer to omit the method.