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

Show more meaningful JSON errors #1423

Open
kzantow opened this issue Dec 22, 2022 · 1 comment
Open

Show more meaningful JSON errors #1423

kzantow opened this issue Dec 22, 2022 · 1 comment
Labels
enhancement New feature or request json Regarding JSON output

Comments

@kzantow
Copy link
Contributor

kzantow commented Dec 22, 2022

What would you like to be added:
When attempting to decode Syft JSON (or other formats), error messages do not show what line/character an error occurred, making it very difficult to understand what's wrong or how to fix it.

Why is this needed:
A user is unable to proceed when unable to parse a Syft JSON file.

Additional context:
It looks like there is a fairly simple way to get more information about parser errors when decoding JSON. See this article.

The gist is, the error returned from json.Unmarshal needs to be tested for types: *json.SyntaxError and *json.UnmarshalTypeError. Both of these types provide a .Offset field which is the character offset where an error occurred. From there we can write a simple function to extract the line text, line number, and character number to provide a nicely formatted message about the error, something like:

invalid JSON input line 256 (expected number):
>     "field": "value",
>              ^

The original function outlined in the article is, which could easily be modified for our needs:

func lineAndCharacter(input string, offset int) (line int, character int, err error) {
	lf := rune(0x0A)

	if offset > len(input) || offset < 0 {
		return 0, 0, fmt.Errorf("Couldn't find offset %d within the input.", offset)
	}

	// Humans tend to count from 1.
	line = 1

	for i, b := range input {
		if b == lf {
			line++
			character = 0
		}
		character++
		if i == offset {
			break
		}
	}

	return line, character, nil
}

This is related to #1351

@kzantow kzantow added the enhancement New feature or request label Dec 22, 2022
@kzantow kzantow self-assigned this Dec 22, 2022
@wagoodman wagoodman added the json Regarding JSON output label Feb 23, 2023
@wagoodman
Copy link
Contributor

Are there any other JSON libs that can help further identify these kinds of errors?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request json Regarding JSON output
Projects
Status: Ready
Development

No branches or pull requests

2 participants