Fix bug handling invalid json

Also improve test coverage.