kolypto / j2cli

Jinja2 Command-Line Tool, reworked

Home Page:http://pypi.python.org/pypi/j2cli

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

JSON array as argument throws ValueError

slisznia opened this issue · comments

I have a JSON array of objects that I'm trying to pass to the template. I'm getting
ValueError: dictionary update sequence element #0 has length 7; 2 is required

To make it work, I have to wrap the array into another JSON object of single element:
{ "data": [..] }

then pass that to the j2. I should be able to work directly with the array?

commented

Will you please give me a sample (if the issue is still relevant)?

Hi, I have the same question. Here is an example. I have a j2cli template to generate some Postgres SQL given a list of JSON items:

{% for entry in entries %}

insert into table (download_url, filename, publish_date)
values ('{{ entry.download_url }}', '{{ entry.filename }}', '{{ entry.publish_date }}');

{% endfor %}

I also have a sample list of items in a JSON file:

[
  {
    "download_url": "http://server.somewhere/this_is_the_filename.pdf",
    "filename": "this_is_the_filename.pdf",
    "publish_date": "2021-09-03"
  }
]

I try to run this thru j2cli:

j2 -f json pginsert.j2 data.json

... but I get an error:

Traceback (most recent call last):
  File "/usr/local/bin/j2", line 8, in <module>
    sys.exit(main())
  File "/usr/local/lib/python3.9/site-packages/j2cli/cli.py", line 202, in main
    output = render_command(
  File "/usr/local/lib/python3.9/site-packages/j2cli/cli.py", line 186, in render_command
    result = renderer.render(args.template, context)
  File "/usr/local/lib/python3.9/site-packages/j2cli/cli.py", line 85, in render
    return self._env \
  File "/usr/local/lib/python3.9/site-packages/jinja2/environment.py", line 1086, in render
    vars = dict(*args, **kwargs)
ValueError: dictionary update sequence element #0 has length 3; 2 is required

I have used entries in the template, but I don't know what to call the top-level array [] or how to access it.

If I wrap the JSON array with literally anything, then I have a name to use (in this case 'entries'):

{
  "entries": [
    {
      "download_url": "http://server.somewhere/this_is_the_filename.pdf",
      "filename": "this_is_the_filename.pdf",
      "publish_date": "2021-09-03"
    }
  ]
}

Is it supported to access the top-level JSON without any handle?

Thanks,