Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avro union - remove type information in resulting json #434

Closed
HIngelhag opened this issue Apr 25, 2023 · 1 comment
Closed

Avro union - remove type information in resulting json #434

HIngelhag opened this issue Apr 25, 2023 · 1 comment

Comments

@HIngelhag
Copy link

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
Copy link
Owner

mtth commented Apr 30, 2023

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.

@mtth mtth closed this as completed May 24, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants