typescript-json-decoder icon indicating copy to clipboard operation
typescript-json-decoder copied to clipboard

Failed to decode nested fields

Open bekverdyan opened this issue 3 years ago • 1 comments

I'm trying to decode nested values from JSON like this:

{
  name: 'exo',
    code: '1212',
      nested: {
    name: 'lika',
      code: '020202',
        place: 'somewhere'
  },
  other1: 'oooo',
    other2: 8989
}

and got an error:

The value `undefined` is not of type `string`, but is of type `undefined`
when trying to decode the key `place` in `{"name":"exo","code":"1212","nested":{"name":"lika","code":"020202","place":"somewhere"},"other1":"oooo","other2":8989}

This is my decoder function:

const dataDecoder = record({
  name: field('nested', field('name', string)),
  place: field('nested', field('place', string))
});

How can I decode values from nested objects?

bekverdyan avatar Sep 13 '22 10:09 bekverdyan

Thanks creating an issue!

I see you're trying to flatten the structure in the same pass as decoding. I'm sorry there isn't really a good way of doing this, but I see several people wanting to do the same thing, so I have some ideas on how to make this more ergonomic. Although your solution here seems to be kind of clean, so I will see if it's possible to support it as well! The reason it doesn't work is that field is really just a helper function, and specifically only works when used directly inside a record, while nesting them like in your example isn't something I've considered.

A solution in the meantime you can use is the more general fields decoder, like this (although it is more verbose and annoying to do it this way):

const dataDecoder = record({
  name: fields({ nested: { name: string } }, (x) => x.nested.name),
  place: fields({ nested: { place: string } }, (x) => x.nested.place)
});

tskj avatar Sep 13 '22 12:09 tskj