Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Invalid JSON output when no rows #328

Closed
gravis opened this issue Sep 22, 2021 · 3 comments
Closed

Invalid JSON output when no rows #328

gravis opened this issue Sep 22, 2021 · 3 comments
Labels
bug Something isn't working

Comments

@gravis
Copy link

gravis commented Sep 22, 2021

sqlite-utils query generates a JSON output with the result from the query:

[{...},{...}]

If no rows are returned by the query, I'm expecting an empty JSON array:

[]

But actually I'm getting an empty string. To be consistent, the output should be [] when the request succeeds (return code == 0).

@simonw simonw added the bug Something isn't working label Sep 22, 2021
@simonw
Copy link
Owner

simonw commented Sep 22, 2021

Good catch, thanks.

@simonw
Copy link
Owner

simonw commented Sep 22, 2021

The bug is in this code:

def output_rows(iterator, headers, nl, arrays, json_cols):
# We have to iterate two-at-a-time so we can know if we
# should output a trailing comma or if we have reached
# the last row.
current_iter, next_iter = itertools.tee(iterator, 2)
next(next_iter, None)
first = True
for row, next_row in itertools.zip_longest(current_iter, next_iter):
is_last = next_row is None
data = row
if json_cols:
# Any value that is a valid JSON string should be treated as JSON
data = [maybe_json(value) for value in data]
if not arrays:
data = dict(zip(headers, data))
line = "{firstchar}{serialized}{maybecomma}{lastchar}".format(
firstchar=("[" if first else " ") if not nl else "",
serialized=json.dumps(data, default=json_binary),
maybecomma="," if (not nl and not is_last) else "",
lastchar="]" if (is_last and not nl) else "",
)
yield line
first = False

@simonw simonw closed this as completed in 7427a91 Sep 22, 2021
@gravis
Copy link
Author

gravis commented Sep 22, 2021

Wow, that was fast! Thank you!

simonw added a commit that referenced this issue Sep 22, 2021
simonw added a commit that referenced this issue Nov 15, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants