Skip to content

Commit

Permalink
add a fallback to JSON parser if the YAML one fails
Browse files Browse the repository at this point in the history
  • Loading branch information
Thomas Kliszowski committed Dec 23, 2015
1 parent 63965e4 commit e0a2349
Show file tree
Hide file tree
Showing 6 changed files with 34 additions and 8 deletions.
3 changes: 1 addition & 2 deletions JSONReindent.sublime-settings
@@ -1,4 +1,3 @@
{
"sort_keys": false,
"strict_decoder": false
"sort_keys": false
}
6 changes: 1 addition & 5 deletions json_reindent/__init__.py
@@ -1,13 +1,9 @@
import yaml
import json
import logging
from .utils import ordered_load

logger = logging.getLogger(__name__)


def parse_input(content, *args, **kwargs):
return ordered_load(content, yaml.SafeLoader, *args, **kwargs)
return ordered_load(content, *args, **kwargs)


def format_output(data, indent=2, separators=[',', ': '], sort_keys=False, ensure_ascii=False):
Expand Down
22 changes: 21 additions & 1 deletion json_reindent/utils.py
@@ -1,13 +1,33 @@
import json
import yaml
import collections
import logging

logger = logging.getLogger(__name__)

def ordered_load(stream, Loader=yaml.Loader, use_collections=True):

def ordered_load(stream, use_collections=True):
if use_collections and hasattr(collections, 'OrderedDict'):
object_pairs_hook = collections.OrderedDict
else:
object_pairs_hook = dict

try:
return yaml_ordered_load(stream, object_pairs_hook)
except Exception as e:
logger.error(e, exc_info=True)

return json_ordered_load(stream, object_pairs_hook)


def json_ordered_load(stream, object_pairs_hook):
return json.loads(
stream,
strict=False,
object_pairs_hook=object_pairs_hook)


def yaml_ordered_load(stream, object_pairs_hook, Loader=yaml.Loader):
class OrderedLoader(Loader):
pass

Expand Down
4 changes: 4 additions & 0 deletions tests/static/fail_yaml/result.json
@@ -0,0 +1,4 @@
{
"deviceID": "99d5ce418b134705",
"_useragent": "android\/app\/4.4"
}
1 change: 1 addition & 0 deletions tests/static/fail_yaml/test.json
@@ -0,0 +1 @@
{"deviceID":"99d5ce418b134705","_useragent":"android\/app\/4.4"}
6 changes: 6 additions & 0 deletions tests/test_base.py
Expand Up @@ -33,3 +33,9 @@ def test_no_collections():
data = parse_input(get_static_content('base/test.json'), use_collections=False)
output = format_output(data)
assert json.loads(output) == json.loads(get_static_content('base/result.json'))


def test_fail_yaml():
data = parse_input(get_static_content('fail_yaml/test.json'))
output = format_output(data)
assert json.loads(output) == json.loads(get_static_content('fail_yaml/result.json'))

0 comments on commit e0a2349

Please sign in to comment.