Hjson for Python

Overview

hjson-py

Build Status PyPI version

Hjson, a user interface for JSON

Hjson Intro

Hjson works with Python 2.5+ and Python 3.3+

The Python implementation of Hjson is based on simplejson. For other platforms see hjson.github.io.

Installation

pip will also add the hjson tool to your PATH (try echo '{a:1}'|hjson).

Commandline

Usage:
  hjson [options]
  hjson [options] <input>
  hjson (-h | --help)
  hjson (-V | --version)

Options:
  -h --help     Show this screen.
  -j            Output as formatted JSON.
  -c            Output as JSON.
  -V --version  Show version.

E.g. echo '{"json":"obj"}' | hjson

Usage

import hjson

Decoding Hjson

text = """{
  foo: a
  bar: 1
}"""

hjson.loads(text)

Result:

OrderedDict([('foo', 'a'), ('bar', 1)])

Encoding Python object hierarchies

hjson.dumps({'foo': 'text', 'bar': (1, 2)})

Result:

{
  foo: text
  bar:
  [
    1
    2
  ]
}

Encoding as JSON

Note that this is probably not as performant as the simplejson version.

hjson.dumpsJSON(['foo', {'bar': ('baz', None, 1.0, 2)}])

Result: '["foo", {"bar": ["baz", null, 1.0, 2]}]'

API

hjson-py documentation

History

see history.md

Comments
  • Pypi release version mismatch.

    Pypi release version mismatch.

    Pypi release is 3.0.1 uploaded the Oct 27, 2017 but the latest github release is 3.6.5 on Oct 24, 2014.

    Which release is the most updated and why both sites don't have the same version? Thanks in advance.

    opened by alferguet 11
  • Error with lines that open with `{` and space.

    Error with lines that open with `{` and space.

    I am getting an error over this line ... https://github.com/stackstrap/environment/blob/master/environment/init.sls#L14

    HjsonDecodeError: Key names that include {}[],: or whitespace require quotes at: line 14 column 5 (char 218)
    

    To me this should work... It is probable that the error roots with the whitespace between the { and the t, but that is not very intuitive if it is the case. Could this be resolved?

    Thanks!

    opened by howardroark 8
  • Change from scripts to entry_points in setup.py

    Change from scripts to entry_points in setup.py

    Hi there,

    I've added a conda-forge package for hjson-py (available at https://anaconda.org/conda-forge/hjson-py) and it was recommended at https://github.com/conda-forge/staged-recipes/pull/19022#discussion_r884137576 to change the scripts section in setup.py to entry_points: console_scripts instead so that noarch (i.e. cross-platform) can be used. Here's a patch for this.

    To test, clone the branch and do:

    pip install -e .
    hjson --help
    

    Fixes #20, fixes #22

    References:

    • https://packaging.python.org/en/latest/guides/distributing-packages-using-setuptools/#console-scripts
    • https://stackoverflow.com/questions/18787036/difference-between-entry-points-console-scripts-and-scripts-in-setup-py
    opened by weiji14 3
  • Round-trip with hjson-js

    Round-trip with hjson-js

    Hi, Many thanks again for this project!

    This PR must not be merged and is intended as a general discussion: should we turn ensure_ascii to False by default when encoding HJSON into JSON?

    I noticed when using the python implementation that hjson -j writes any non ascii character gets escaped as a unicode character. This is the hack I have done to keep é as is instead of turning it into \u00E9 Once that is done, I get a perfect round-trip to the original JSON generated by nodejs.

    Let me know. Cheers!

    opened by hmalphettes 3
  • Having '=' as key separator?

    Having '=' as key separator?

    I find = symbol even more human readable for even simpler JSON alternative.

    And the fact that you can skip braces at the root object make it look almost like *.INI files, yet with hierarchical functionality.

    class = content.Medal
    components = [
        {
            class = content.components.IconComponent
            icon = medal-tournament-1
            tag = client
        }
        {
            class = content.components.UnlockSoundComponent
            sound = achievement-unlocked-snd
            tag = client
        }
    ]
    description = MEDAL_TOURNAMENT_1_DESC
    name = MEDAL_TOURNAMENT_1
    

    How can I add = as a "alternative", yet allowed key separator? Or at least replace : with = for my own personal use (I understand that this would break the original JSON compatibility, but for sake of even more convenience, I would like to do that)?

    opened by desertkun 3
  • Issue parsing hjson

    Issue parsing hjson

    Hey!

    So I am attempting to get this running with Salt but the parser seems to not like what it is getting. I think something left over is getting in the way. Basically pure JSON works fine, but hjson is failing.

    Here is the input (keep in mind that the first line is stripped out before parsing):

    #! hjson
    
    {
      redis-server: pkg.installed
    }
    

    Here is the error which is passed back from Salt:

    local:
        Data failed to compile:
    ----------
        Rendering SLS test failed, render error: Bad name at: line 3 column 3 (char 5)
    Traceback (most recent call last):
      File "/home/vagrant/salt/salt/state.py", line 2469, in render_state
        sls, rendered_sls=mods
      File "/home/vagrant/salt/salt/template.py", line 79, in compile_template
        ret = render(input_data, saltenv, sls, **render_kwargs)
      File "/home/vagrant/salt/salt/renderers/hjson.py", line 36, in render
        return hjson.loads(hjson_data)
      File "/usr/local/lib/python2.7/dist-packages/hjson/__init__.py", line 464, in loads
        return _default_decoder.decode(s)
      File "/usr/local/lib/python2.7/dist-packages/hjson/decoder.py", line 450, in decode
        obj, end = self.raw_decode(s)
      File "/usr/local/lib/python2.7/dist-packages/hjson/decoder.py", line 482, in raw_decode
        return self.scan_once(s, idx)
      File "/usr/local/lib/python2.7/dist-packages/hjson/scanner.py", line 94, in scan_once
        return _scan_once(string, idx)
      File "/usr/local/lib/python2.7/dist-packages/hjson/scanner.py", line 79, in _scan_once
        _scan_once, object_hook, object_pairs_hook, memo)
      File "/usr/local/lib/python2.7/dist-packages/hjson/decoder.py", line 300, in JSONObject
        key, end = scankey(s, end, encoding, strict)
      File "/usr/local/lib/python2.7/dist-packages/hjson/decoder.py", line 275, in scankey
        raise JSONDecodeError("Bad name at", s, begin)
    JSONDecodeError: Bad name at: line 3 column 3 (char 5)
    
    opened by howardroark 3
  • HJSON file with only comments will error out

    HJSON file with only comments will error out

    This is a minor bug I've noticed. If the HJSON file contains only a comment, it will error out. Using the HJSON linter at https://hjson.org/try.html, an empty object {} was created.

    Python 2.7.12 (default, Oct 11 2016, 05:20:59)
    [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.38)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import hjson
    >>> hjson.loads('//File with only comments')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/Users/sonnyvan/.virtualenvs/test/lib/python2.7/site-packages/hjson/__init__.py", line 173, in loads
        return _default_decoder.decode(s)
      File "/Users/sonnyvan/.virtualenvs/test/lib/python2.7/site-packages/hjson/decoder.py", line 514, in decode
        obj, end = self.raw_decode(s)
      File "/Users/sonnyvan/.virtualenvs/test/lib/python2.7/site-packages/hjson/decoder.py", line 558, in raw_decode
        raise e
    hjson.scanner.HjsonDecodeError: Bad key name (eof): line 1 column 36 (char 35)
    >>>
    
    opened by mochi99999 2
  • The `hjson` script is b0rken because it does not use console_scripts

    The `hjson` script is b0rken because it does not use console_scripts

    The consle_scripts of setup.py should be used.

    The hjson file in bin of the python prefix now says

    
    python -m hjson.tool "$@"
    

    And it won't do, since I didn't install this to Python 2 on my Ubuntu.

    opened by ztane 1
  • HJSON cannot handle a backslash character

    HJSON cannot handle a backslash character

    It's not possible to encode a string with a backslash with this HJSON parser.

    # A single slash won't work - empty string
    # OrderedDict([('test', '')])
    hjson.loads('''{"test": "\"}''')
    
    # An escaped slash won't either
    # HjsonDecodeError: Unterminated string starting at: line 1 column 10 (char 9)
    hjson.loads('''{"test": "\\"}''')
    
    opened by mattmc3 1
  • Parsing exception for empty multiline strings

    Parsing exception for empty multiline strings

    Empty multiline strings are not being parsed correctly:

    import hjson
    
    hjson.loads("""
    
    hello: ""
    
    """)
    # OrderedDict([('hello', '')])
    
    hjson.loads("""
    
    hello: ''
    
    """)
    # OrderedDict([('hello', '')])
    
    hjson.loads("""
    
    hello: ''''''
    
    """)
    # Traceback (most recent call last):
    # ...
    # File "/hpcdata/odkuuf/ENV_CONDA/BEAVER/dev/lib/python3.6/site-packages/hjson/decoder.py", line 203, in mlscanstring
    #     if string[-1] == '\n':
    # IndexError: string index out of range
    
    hjson.loads("""
    
    hello: '''
    '''
    
    """)
    # Traceback (most recent call last):
    # ...
    # File "/hpcdata/odkuuf/ENV_CONDA/BEAVER/dev/lib/python3.6/site-packages/hjson/decoder.py", line 203, in mlscanstring
    #     if string[-1] == '\n':
    # IndexError: string index out of range
    
    
    hjson.loads("""
    
    hello: '''
    
    '''
    
    """)
    # OrderedDict([('hello', '')])
    
    opened by kenodegard 1
  • Default indent behavior of hjson.dumps does not match documentation

    Default indent behavior of hjson.dumps does not match documentation

    Documentation says:

    If ``indent`` is a string, then JSON array elements and object members
    will be pretty-printed with a newline followed by that string repeated
    for each level of nesting. ``None`` (the default) selects the most compact
    representation without any newlines. 
    

    Note that the default, ident=None, should produce a compact string without any newlines.

    Expected behavior:

    >>> import hjson
    >>> d = dict(a=1, b=2)
    >>> hjson.dumps(d)
    '{a: 1, b: 2}'
    

    Actual behavior:

    >>> hjson.dumps(d)
    '{\n  a: 1\n  b: 2\n}'
    
    opened by teichert 1
  • Claimed to support py27, fails to install

    Claimed to support py27, fails to install

    DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support pip 21.0 will remove support for this functionality.
    Collecting hjson
      Downloading hjson-3.1.0.tar.gz (40 kB)
         |████████████████████████████████| 40 kB 1.0 MB/s
        ERROR: Command errored out with exit status 1:
         command: /opt/local/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/jt/83jw43hn0nl97jgxmswvvdh40000gn/T/pip-install-raiNzN/hjson/setup.py'"'"'; __file__='"'"'/private/var/folders/jt/83jw43hn0nl97jgxmswvvdh40000gn/T/pip-install-raiNzN/hjson/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/jt/83jw43hn0nl97jgxmswvvdh40000gn/T/pip-pip-egg-info-y1eBgO
             cwd: /private/var/folders/jt/83jw43hn0nl97jgxmswvvdh40000gn/T/pip-install-raiNzN/hjson/
        Complete output (6 lines):
        Traceback (most recent call last):
          File "<string>", line 1, in <module>
          File "/private/var/folders/jt/83jw43hn0nl97jgxmswvvdh40000gn/T/pip-install-raiNzN/hjson/setup.py", line 80
            **kw,
                ^
        SyntaxError: invalid syntax
        ----------------------------------------
    ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
    
    opened by bashu 0
  • Keep comments

    Keep comments

    This allows for comments to be kept and dumped back into file.

    Currently supports: /* Block comments over multiple lines */ // Single line comments # Single line hash comments

    Does not support in line comments such as: { pi: 3.1415 // This is pi }

    Usage: fp = open("testFile.hjson") configObject, commentPositions = loadWithComments(fp=fp) fp.close()

    fp = open('newFile.hjson', 'w') dumpWithComments(fp, configObject, commentPositions) fp.close()

    OR: fp = open("testFile.hjson") configObject, commentPositions = loadsWithComments(s=fp.read()) fp.close()

    dumpedString = dumpsWithComments(configObject, commentPositions) fp = open('newFile.hjson', 'w') fp.write(dumpedString) fp.close()

    Note: As long as the key names of the loaded dictionary object isn't changed by the program or the order of the items isn't changed, everything should be fine.

    opened by BdT141 0
  • dump method breaks links

    dump method breaks links

    When I write some info such as

    contact_info: {
        name: Isabella
        contact_card_url: https://something.org/whatever
    }
    

    if I try to append to this the hjson parser interprets this :// as some sort of key, I guess, and it breaks my previously working link.

    opened by isinyaaa 0
  • floats ending with '.0' turns into ints

    floats ending with '.0' turns into ints

    This hjson: { test: 1.0 }

    turns into {test: 1} after hjson.loads(). A type() call says it is an int. Maybe this is the wanted behavior? I just expected something else. "Normal" json returns a float.

    opened by jonathankarlsson 1
  • Round-tripping comments?

    Round-tripping comments?

    According to the HJson FAQ:

    Hjson allows you to round-trip your data, including your comments.

    • But not yet with all implementations, PRs welcome :)

    Unless I'm mistaken, hjson-py does not round-trip comments. Is there a plan to support it in the future?

    I would gladly (try to) contribute a PR, so I had a look at the source. However it seems to me that such a feature would require a heavy refactoring of the data-structures involved, and possibly also of the parsing functions. Or did I miss something?

    opened by pchampin 3
Owner
Hjson
A user interface for JSON.
Hjson
Repository for learning Python (Python Tutorial)

Repository for learning Python (Python Tutorial) Languages and Tools ?? Overview ?? Repository for learning Python (Python Tutorial) Languages and Too

Swiftman 2 Aug 22, 2022
A python package to avoid writing and maintaining duplicated python docstrings.

docstring-inheritance is a python package to avoid writing and maintaining duplicated python docstrings.

Antoine Dechaume 15 Dec 7, 2022
advance python series: Data Classes, OOPs, python

Working With Pydantic - Built-in Data Process ========================== Normal way to process data (reading json file): the normal princiople, it's f

Phung Hưng Binh 1 Nov 8, 2021
A comprehensive and FREE Online Python Development tutorial going step-by-step into the world of Python.

FREE Reverse Engineering Self-Study Course HERE Fundamental Python The book and code repo for the FREE Fundamental Python book by Kevin Thomas. FREE B

Kevin Thomas 7 Mar 19, 2022
A simple USI Shogi Engine written in python using python-shogi.

Revengeshogi My attempt at creating a USI Shogi Engine in python using python-shogi. Current State of Engine Currently only generating random moves us

null 1 Jan 6, 2022
Python-slp - Side Ledger Protocol With Python

Side Ledger Protocol Run python-slp node First install Mongo DB and run the mong

Solar 3 Mar 2, 2022
Python-samples - This project is to help someone need some practices when learning python language

Python-samples - This project is to help someone need some practices when learning python language

Gui Chen 0 Feb 14, 2022
Valentine-with-Python - A Python program generates an animation of a heart with cool texts of your loved one

Valentine with Python Valentines with Python is a mini fun project I have coded.

Niraj Tiwari 4 Dec 31, 2022
A curated list of awesome tools for Sphinx Python Documentation Generator

Awesome Sphinx (Python Documentation Generator) A curated list of awesome extra libraries, software and resources for Sphinx (Python Documentation Gen

Hyunjun Kim 831 Dec 27, 2022
API Documentation for Python Projects

API Documentation for Python Projects. Example pdoc -o ./html pdoc generates this website: pdoc.dev/docs. Installation pip install pdoc pdoc is compat

mitmproxy 1.4k Jan 7, 2023
🏆 A ranked list of awesome python developer tools and libraries. Updated weekly.

Best-of Python Developer Tools ?? A ranked list of awesome python developer tools and libraries. Updated weekly. This curated list contains 250 awesom

Machine Learning Tooling 646 Jan 7, 2023
Run `black` on python code blocks in documentation files

blacken-docs Run black on python code blocks in documentation files. install pip install blacken-docs usage blacken-docs provides a single executable

Anthony Sottile 460 Dec 23, 2022
Legacy python processor for AsciiDoc

AsciiDoc.py This branch is tracking the alpha, in-progress 10.x release. For the stable 9.x code, please go to the 9.x branch! AsciiDoc is a text docu

AsciiDoc.py 178 Dec 25, 2022
📖 Generate markdown API documentation from Google-style Python docstring. The lazy alternative to Sphinx.

lazydocs Generate markdown API documentation for Google-style Python docstring. Getting Started • Features • Documentation • Support • Contribution •

Machine Learning Tooling 118 Dec 31, 2022
A Python module for creating Excel XLSX files.

XlsxWriter XlsxWriter is a Python module for writing files in the Excel 2007+ XLSX file format. XlsxWriter can be used to write text, numbers, formula

John McNamara 3.1k Dec 29, 2022
API spec validator and OpenAPI document generator for Python web frameworks.

API spec validator and OpenAPI document generator for Python web frameworks.

1001001 249 Dec 22, 2022
Materi workshop "Light up your Python!" Himpunan Mahasiswa Sistem Informasi Fakultas Ilmu Komputer Universitas Singaperbangsa Karawang, 4 September 2021 (Online via Zoom).

Workshop Python UNSIKA 2021 Materi workshop "Light up your Python!" Himpunan Mahasiswa Sistem Informasi Fakultas Ilmu Komputer Universitas Singaperban

Eka Putra 20 Mar 24, 2022
Exercism exercises in Python.

Exercism exercises in Python.

Exercism 1.3k Jan 4, 2023
This is a repository for "100 days of code challenge" projects. You can reach all projects from beginner to professional which are written in Python.

100 Days of Code It's a challenge that aims to gain code practice and enhance programming knowledge. Day #1 Create a Band Name Generator It's actually

SelenNB 2 May 12, 2022