Giter VIP home page Giter VIP logo

jsondate's Introduction

jsondate

Sick of rewriting the same JSON datetime handling code for each project? jsondate is a drop-in replacement for Python's standard json library that adds sensible handling of datetime and date objects.

jsondate uses ISO8601 for encoding datetime objects and the date-specific part of ISO6801 for encoding date objects.

Example:

import datetime
import jsondate as json

>>> data = json.dumps(dict(created_at=datetime.datetime(2012, 10, 31)))
'{"created_at": "2012-10-31T00:00:00Z"}'

>>> json.loads(data)
{u'created_at': datetime.datetime(2012, 10, 31, 0, 0)}

>>> date = json.dumps(dict(date=datetime.date(2012, 10, 31)))
'{"date": "2012-10-31"}'

>>> json.loads(data)
{u'created_at': datetime.date(2012, 10, 31)}

Unicode Empty Strings

The json standard library module will return unicode objects for all strings except empty strings, which are returned as str objects.

This inconsistency can be annoying when using libraries that expect all input to be unicode.

jsondate fixes this by returning empty-strings as unicode objects as well.

jsondate's People

Contributors

rconradharris avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

jsondate's Issues

decode every datetime string to datetime object is not always the best option

if I have a field like datetime_str which I expected it to be exactly a datetime string . but by using jsondate. this field will always be decoded to datetime object... which is not what I want.

{ 'a': '20130101', 'b': datetime(2012,01,01) }
dumps_str = dumps(  {'a': '20130101',      do your magic on 'b' } )
loads( dumps_str )  # the same,  do your magic on 'b' only

maybe this this the main reason why pymongo bson.json_util convert datetime object into a dict instead.

   {'a': 'hi' , 'b': datetime(2011,1,1)} 
 => 
   {'a': 'hi', 'b': {'$date': '20110101' } }

Tests fail: No module named 'StringIO'

==================================================================================== test session starts =====================================================================================
platform freebsd13 -- Python 3.9.13, pytest-7.1.2, pluggy-1.0.0 -- /usr/local/bin/python3.9
cachedir: .pytest_cache
hypothesis profile 'default' -> database=DirectoryBasedExampleDatabase('/disk-samsung/freebsd-ports/devel/py-jsondate/work-py39/jsondate-0.1.2/.hypothesis/examples')
rootdir: /disk-samsung/freebsd-ports/devel/py-jsondate/work-py39/jsondate-0.1.2
plugins: forked-1.4.0, hypothesis-6.53.0, xdist-2.5.0, cov-2.9.0, typeguard-2.13.3, mock-1.10.4, asyncio-0.18.3, trio-0.7.0, flaky-3.7.0, subtests-0.8.0, rerunfailures-10.1, timeout-2.1.0, flake8-1.1.1, isort-3.0.0
asyncio: mode=legacy
collected 0 items / 1 error                                                                                                                                                                  

=========================================================================================== ERRORS ===========================================================================================
__________________________________________________________________________ ERROR collecting tests/test_jsondate.py ___________________________________________________________________________
ImportError while importing test module '/disk-samsung/freebsd-ports/devel/py-jsondate/work-py39/jsondate-0.1.2/tests/test_jsondate.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/usr/local/lib/python3.9/importlib/__init__.py:127: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
tests/test_jsondate.py:4: in <module>
    import StringIO
E   ModuleNotFoundError: No module named 'StringIO'
====================================================================================== warnings summary ======================================================================================
../../../../../../usr/local/lib/python3.9/site-packages/pytest_asyncio/plugin.py:191
  /usr/local/lib/python3.9/site-packages/pytest_asyncio/plugin.py:191: DeprecationWarning: The 'asyncio_mode' default value will change to 'strict' in future, please explicitly use 'asyncio_mode=strict' or 'asyncio_mode=auto' in pytest configuration file.
    config.issue_config_time_warning(LEGACY_MODE, stacklevel=2)

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
================================================================================ 1 warning, 1 error in 0.66s =================================================================================
*** Error code 2

Version: 0.1.2
Python-3.9
FreeBSD 13.1

Transfer project to new maintainer

Hello,

I'm the director of Free Law Project (https://github.com/freelawproject). We've become dependent on jsondate and we want to upgrade it to py3. This library feels pretty much abandoned, so I wonder if we can take it over somehow. It's a very small library, so I think that'd just mean:

  • Figuring out how to transfer the code to us on Github

  • Figuring out how to transfer the pypi things to us so we can upload new versions

  • Working out any licensing issues (looks like it's MIT, so should be easy).

We've already vendored the code in freelawproject/juriscraper#249 and are considering a fork, but it'd be much better to get this one fixed and alive again.

Thank you,

Mike

Problem decoding RavenDB content when attribute value is a dict

Results returned from RavenDB contain a dict entry called @metadata which has a value which itself is a dict:
{'@metadata': {'Temp-Index-Score': 1.41421354}, 'document_id': '104068/1951-01-01', ...
This throws in jsondate__init
.datetime_decoder, first line:
for key, value in dict
.iteritems():
with AttributeError: 'dict' object has no attribute 'iteritems'

The problem appears to be in the scanner, but I can't pinpoint any further as the working of make_scanner are a bit opaque.

load()/loads() doesn't handle date/datetime values that aren't contained in a dict

load()/loads() doesn't handle date/datetime values that aren't contained in a dict. It appears that the object_hook callback is only useful for objects, not for other types. From what I can see, the json module only offers hooks for objects, ints and floats, not strings. :(

>>> import datetime
>>> import jsondate as json
>>> date = datetime.date(2014, 12, 22)
>>> dumped = json.dumps(date)
>>> print dumped
"2014-12-22"
>>> loaded = json.loads(dumped)
>>> print loaded
2014-12-22
>>> date = [datetime.date(2014, 12, 22)]
>>> dumped = json.dumps(date)
>>> print dumped
["2014-12-22"]
>>> loaded = json.loads(dumped)
>>> print loaded
[u'2014-12-22']

Example from the README fails: AttributeError: 'dict' object has no attribute 'iteritems'

$ python3.9
Python 3.9.13 (main, Aug  6 2022, 21:09:10) 
[Clang 14.0.5 (https://github.com/llvm/llvm-project.git llvmorg-14.0.5-0-gc1238 on freebsd13
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> import jsondate as json
>>> data = json.dumps(dict(created_at=datetime.datetime(2012, 10, 31)))
>>> print(data)
{"created_at": "2012-10-31T00:00:00Z"}
>>> json.loads(data)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.9/site-packages/jsondate/__init__.py", line 51, in loads
    return json.loads(*args, **kwargs)
  File "/usr/local/lib/python3.9/json/__init__.py", line 359, in loads
    return cls(**kw).decode(s)
  File "/usr/local/lib/python3.9/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/lib/python3.9/json/decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
  File "/usr/local/lib/python3.9/site-packages/jsondate/__init__.py", line 18, in _datetime_decoder
    for key, value in dict_.iteritems():
AttributeError: 'dict' object has no attribute 'iteritems'

Support python3

Looks like this would be fairly easy. There's even a fork that seems to already be working on this.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.