Skip to content

How to get the actual typeof(<JSON Array Element>).name ? #22817

Discussion options

You must be logged in to vote

Yes, the inverse would be:

import json

type Elem = string | f64

elems := json.decode([]Elem, '["ABC",123,4.56]')!
for elem in elems {
	match elem {
		string {
			println('string: ${elem}')	
		}
		f64 {
			println('float: ${elem}')
		}
	}
}

The result of the above is:

string: ABC
float: 123.0
float: 4.56

And more work is needed to get apart the ints from the floats.

Imho using a bag in json holding an array of diverse objects is sooner or later more difficult too handle.

I'll prefer to have an array with named elements, for instance:

import json

struct Samples {
	ys    []f64
	xs    []int
	units string
}

samples := Samples{
	ys: [ 0.0, 10.3, 20.5 ]
	xs: [ 0, 1, 2 ]
	units: 'ohms/sec'
}

Replies: 2 comments 3 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
3 replies
@retoxing
Comment options

@jorgeluismireles
Comment options

Answer selected by retoxing
@retoxing
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants