Loop over object

1,786 views
Skip to first unread message

Trevor Hartman

unread,
Mar 8, 2016, 12:53:20 PM3/8/16
to Jsonnet
I looked in the docs, mailing list and GitHub issues, but couldn't find anything on looping over objects. Here's a made-up example of what I'm after:

local items = {a: 1, b: 2};

{
  [key + "-node"]: { name: value } 
  for [key,value] in items
}

I also tried:

{
  [item + "-node"]: {
    name: items[item]
  } for item in items
}


Possible? Thanks.

Trevor Hartman

unread,
Mar 8, 2016, 1:00:03 PM3/8/16
to Jsonnet
Of course I find an example right after I post!


So my example would look like:

local items = {a: 1, b: 2};

{
  [item + "-node"]: {
    name: items[item]
  } for item in std.objectFields(items)
}

Hopefully that helps someone in the future.

🤘

Dave Cunningham

unread,
Mar 8, 2016, 1:07:07 PM3/8/16
to Trevor Hartman, Jsonnet
Thanks for posting the solution, this should be better documented!

Perhaps iterating over objects should be supported, as in Python.  On the other hand, what you're doing is really reflection so there's an argument it should be quite visible in the code that this is happening.

At any rate, I noticed that the current behavior is a weird error message so filed https://github.com/google/jsonnet/issues/121

--
You received this message because you are subscribed to the Google Groups "Jsonnet" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jsonnet+u...@googlegroups.com.
To post to this group, send email to jso...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/jsonnet/0ba8d975-1684-4eb6-8f2b-dc6c6210f46e%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

Trevor Hartman

unread,
Mar 8, 2016, 1:11:56 PM3/8/16
to Jsonnet, trevor...@gmail.com
Also noticed this issue: https://github.com/google/jsonnet/issues/119

Possibly related to be able to destructure objects as arrays of tuples (similar to how it works in Scala or Clojure), like my first attempt. That way you're not relying on reflection. It's also very concise:

{
  [key + "-node"]: { name: value } for [key,value] in items
}

Reply all
Reply to author
Forward
0 new messages