0

In a plugin, I'm using json_decode() to obtain information from somewhere.

I've no control over the json structure, but expect a list of numbers under a key foo:

{
  "foo": [10, 20, 30]
}

How to properly guard my operations with get(l:json_object, 'foo') so that they fail predictably when value received under foo isn't list? E.g. {"foo": null}, {"foo": {"bar": "kaboom"}}:

    let l:foo_list = get(l:json_object, 'foo')

    if __IS_LIST__(l:foo_list)    " <-- FIXME

        let l:hundreds = map(l:foo_list, "10 * v:val")

        echo join(l:hundreds, " -- ")

        " Expected output:
        " 100 -- 200 -- 300
    endif

What this fictional __IS_LIST__ check actually looks like in Vimscript?

4

Try:

if type(l:foo_list) == v:t_list

Or in older versions of Vim:

if type(l:foo_list) == type([])

See :help type() for more details.

2
  • 1
    I still use type([]) for portability reasons. – Luc Hermitte May 5 '20 at 18:05
  • Nice, thanks. I'd expected it was something trivial — but neither :help List nor vim cheatsheet revealed the type function to me; and the question was somehow fruitless on web search. Hopefully, it won't be now. – ulidtko May 6 '20 at 9:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.