- commentjson 0.9.0
- Навигация
- Ссылки проекта
- Статистика
- Метаданные
- Сопровождающие
- Классификаторы
- Описание проекта
- Подробности проекта
- Ссылки проекта
- Статистика
- Метаданные
- Сопровождающие
- Классификаторы
- История выпусков Уведомления о выпусках | Лента RSS
- Загрузка файлов
- Source Distribution
- Хеши для commentjson-0.9.0.tar.gz
- commentjson — Add comments in JSON files¶
- What does commentjson do?¶
- Installation¶
- Basic Usage¶
- API Documentation¶
- Indices and tables¶
- How to add comments in JSON?
- Add comments in JSON
- Add comments in JSON with JavaScript or NodeJS
- Add comments in JSON with 3rd party libraries
- Add comments in JSON with Python
- Add comments in JSON with Go
- Comments
- Follow Us
- Json Comment
- Comments
- Multiline strings
- Custom Methods
- File Load
- File Save
- Install
- Usage
- Examples
- Limitations
- Source
- API
- How to read the API
commentjson 0.9.0
Add Python and JavaScript style comments in your JSON files.
Навигация
Ссылки проекта
Статистика
Метаданные
Сопровождающие
Классификаторы
Описание проекта
===========
commentjson
===========
`commentjson` (Comment JSON) is a Python package that helps you create JSON
files with Python and JavaScript style inline comments. Its API is very similar
to the Python standard library’s `json`_ module.
.. _`json`: http://docs.python.org/2/library/json.html
.. image:: https://travis-ci.org/vaidik/commentjson.png
Installation
============
pip install commentjson
Basic Usage
===========
.. code-block:: python
>>> import commentjson
>>>
>>> json_string = «»» . «name»: «Vaidik Kapoor», # Person’s name
. «location»: «Delhi, India», // Person’s location
.
. # Section contains info about
. // person’s appearance
. «appearance»: . «hair_color»: «black»,
. «eyes_color»: «black»,
. «height»: «6»
. >
. >»»»
>>>
>>> json_loaded = commentjson.loads(json_string)
>>> print json_loaded
, u’name’: u’Vaidik Kapoor’, u’location’: u’Delhi, India’>
Documentation
=============
Complete documentation can be found `here`_.
.. _`here`: http://commentjson.readthedocs.org/en/latest/
Tests
=====
python setup.py test
License
=======
See `license`_.
.. _`license`: https://github.com/vaidik/commentjson/blob/master/LICENSE.rst
Подробности проекта
Ссылки проекта
Статистика
Метаданные
Сопровождающие
Классификаторы
История выпусков Уведомления о выпусках | Лента RSS
Загрузка файлов
Загрузите файл для вашей платформы. Если вы не уверены, какой выбрать, узнайте больше об установке пакетов.
Source Distribution
Uploaded 5 окт. 2020 г. source
Хеши для commentjson-0.9.0.tar.gz
Алгоритм | Хеш-дайджест | |
---|---|---|
SHA256 | 42f9f231d97d93aff3286a4dc0de39bfd91ae823d1d9eba9fa901fe0c7113dd4 | Копировать |
MD5 | fbf45508da35e42f0055b7c4f02d703c | Копировать |
BLAKE2b-256 | c076c4aa9e408dbacee3f4de8e6c5417e5f55de7e62fb5a50300e1233a2c9cb5 | Копировать |
commentjson — Add comments in JSON files¶
commentjson is a Python library that lets you have Python and JavaScript style inline comments in your JSON files. Its API is very similar to the Python Standard library’s json module.
What does commentjson do?¶
commentjson allows you to deserialize JSON files with Python and JavaScript style comments in them. commentjson ’s API is the same as the standard library’s json module. If you are using or like using JSON for configuration files, commentjson can be very handy.
You may put comments in your JSON files like so:
Installation¶
Basic Usage¶
Since commentjson ’s API is the same as standard libraries json module, it is extremely simple to use commentjson . You don’t have to do anything new to use commentjson . Here is what you have to do:
- Write your JSON files by hand or use standard library’s json module or commentjson to create a new JSON file.
- Open the JSON file in your text editor and add comments the same way you would in Python (using # and not docstrings) or the same way you would in JavaScript (using // and not multi-line comments using /** */ ).
- Use commentjson ’s loads or load method to deserialize the file just like how you would use json module to parse a normal JSON string without comments. load and loads will return you a Python object.
>>> import commentjson >>> >>> json_string = """ . "name": "Vaidik Kapoor", # Person's name . "location": "Delhi, India", // Person's location . . # Section contains info about . // person's appearance . "appearance": . "hair_color": "black", . "eyes_color": "black", . "height": "6" . > . >""" >>> >>> json_loaded = commentjson.loads(json_string) >>> print json_loaded , u'name': u'Vaidik Kapoor', u'location': u'Delhi, India'>
API Documentation¶
Deserialize text (a str or unicode instance containing a JSON document with Python or JavaScript like comments) to a Python object.
Serialize obj to a JSON formatted str . Accepts the same arguments as json module in stdlib.
Deserialize fp (a .read() -supporting file-like object containing a JSON document with Python or JavaScript like comments) to a Python object.
- fp – a .read() -supporting file-like object containing a JSON document with or without comments.
- kwargs – all the arguments that json.load accepts.
Serialize obj as a JSON formatted stream to fp (a .write() -supporting file-like object). Accepts the same arguments as json module in stdlib.
- obj – a JSON serializable Python object.
- fp – a .read() -supporting file-like object containing a JSON document with or without comments.
- kwargs – all the arguments that json.dump accepts.
Exception raised when the JSON library in use raises an exception i.e. the exception is not caused by commentjson and only caused by the JSON library commentjson is using.
As of now, commentjson supports only standard library’s json module. It might start supporting other widely-used contributed JSON libraries in the future.
Indices and tables¶
© Copyright 2013, Vaidik Kapoor. Revision 7ef01ea6 .
Versions latest Downloads pdf htmlzip epub On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.
How to add comments in JSON?
JSON don’t support comments by default but we can add that in alternate ways. In this article we have shared how to add comments in JSON with JS, Python & Go.
JSON and API these two terms are really popular nowadays and a vast range of developers are dealing with it daily. JSON seems to be an ideal way to describe data in form of object. However, the last time I was working with a large JSON file I wanted to add some comments to it. I have tried several ways to accomplish the task and in this article we will add comments in JSON with NodeJS, JavaScript, Python and Go.
JSON does not support comments and everything we write inside a JSON is considered as data only. In the early days it had supported comments but later it was removed due to interoperability. However we can always find alternates when we are the one who will format the data and parse it in our application.
Add comments in JSON
The very basic thing that we can do to add comment is to use a designated data element like «__comment» as JSON attribute. When we will parse it in our application we can filter it or structure our application in such a way.
Suppose we have the following JSON file caller user.json
Then we can add comments in JSON as follows
Now the user.json object has 4 attributes and it will not differentiate between the comment and other attributes. We need to filter it manually depending on our use case.
Add comments in JSON with JavaScript or NodeJS
NodeJS is based on JavaScript so we can do the task in similar way. Suppose you are creating a fruit object and want to convert it to JSON and parse it later.
const fruit = < "_comment": "Comment here. ", "name": "Mango", "price": 10 >const jsonData = JSON.stringify(fruit) console.log(jsonData) //
You can see from the above data that the JSON data cant differentiate between our designated data element and regular ones. Lets try to parse teh data and check the output.
console.log(JSON.parse(jsonData)) //
So we can parse the JSON data as usual and can access the comment as var[‘__comment’].
Add comments in JSON with 3rd party libraries
Hjson, a user interface for JSON
Hjson is a pretty amazing tool to not only add comments to a JSON file but also to use JSON without worrying about commas and quotes.
It supports single line as well as multi line comments in JSON.
< // use #, // or /**/ comments, // omit quotes for keys key: 1 // omit quotes for strings contains: everything on this line // omit commas at the end of a line cool: < foo: 1 bar: 2 >// allow trailing commas list: [ 1, 2, ] // and use multiline strings realist: ''' My half empty glass, I will fill your empty half. Now you are half full. ''' >
JSON5 is another promising tool that lets you add comments to JSON file. Here is a quick example below. Follow their documentation to dive deep into the ocean of JSON5.
Add comments in JSON with Python
Python has an inbuilt data type called Dictionary that is similar to JSON. So we can use JSON seamlessly in Python. Lets create a car dictionary.
Now lets add comment to it with help of a designated key value pair and access it as follows.
Add comments in JSON with Go
Lets create a JSON for car with Go lang. Unlike Python or JS the Go version will be a little longer as we have to define struct and convert byte array to string. However Go does not support underscore at the beginning of a struct field so we need to use Comment instead of __comemnt.
package main import ( "fmt" "encoding/json" ) // declaring a struct type Car struct < Name string Brand string Price int Comment string >func main() < car := Car// encoding the struct into json format car_enc, err := json.Marshal(car) if err != nil < // if error is not nil print error fmt.Println(err) >// convert byte array to string fmt.Println(string(car_enc)) // >
So thats is all about JSON comments implementation with various programming languages. Hope it has helped you to understand the process of comments in JSON.
Comments
Effective business manager with 7+ years of experience. Skilled in marketing and financial management. Seeking to increase profitability by 35% at Superior Beverage. At Hex National Group, raised profits 35% in 4 years by controlling costs through directed employee idea programs at all business levels and strategic product development. Created sales-training program resulting in a $2.4M jump in annual revenue in 2 years. https://briansclub.cm/
Best Article i have seen looking for some more detail about Saved as a favorite, I love your web site! https://www.tumblr.com
Coders Diaries is a complete platform for dedicated coders to learn, engage and get hired. The only platform you will ever need.
Follow Us
Json Comment
JSON Comment allows to parse JSON files or strings with:
- Single and Multi line comments
- Multi line data strings
- Trailing commas in objects and arrays, after the last item
This package works with any JSON parser which supports:
by adding a preprocessor to these calls.
Comments
Inline comments are not supported
Multiline strings
Any string can be multiline, even object keys.
- Multiline strings start and end with «»» , like in python
- The preprocessor merges all lines to a single JSON standard string
- A single trailing space per line is kept, if present
- New line is not kept. To hard code new lines in the string, use \\n
Custom Methods
File Load
loadf(path, *args, default = None, **kwargs)
Opens a JSON file with comments. Allows a default value if loading or parsing fails
File Save
dumpf(json_obj, path, *args, indent=4, **kwargs)
Saves a JSON file with indentation
Install
Usage
from jsoncomment import JsonComment string = "[]" json = JsonComment() json_obj = json.loads(string)
Examples
Added in the /examples directory
Limitations
- # , ; , // and /* may be preceded only by whitespaces or tabs on the same line
- */ may be followed only by whitespaces or tabs on the same line
- The trailing comma must be the last character on the same line
Source
Source code available with MIT license on Bitbucket.
API
Added in top level __init__.py
How to read the API
* `User Interface` for common use * `Developer Interface` exposing some internals that could be useful
For each item ( function or class ), there are 2 blocks of comments, above and below item definition:
* The top describes the return values * The bottom describes the item and call variables
If call variables have defaults or use duck typing, every allowed value is described
# return_value # description from .some_module import SomeClass # SomeClass description # ( # variable_1, # description # variable_2 = something, # description # = Default # description of default value ( something ) # = something_2 # description of alternate form ( duck typing ) # )
describes return_value = SomeClass(variable_1, variable_2 = current_value)