Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds Web3.toJSON per #782 #1173

Merged
merged 6 commits into from
Feb 11, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions docs/overview.rst
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,18 @@ Type Conversions
>>> Web3.toInt(hexstr='000F')
15

.. py:method:: Web3.toJSON(obj)

Takes a variety of inputs and returns its JSON equivalent.


.. code-block:: python

>>> Web3.toJSON(3)
'3'
>>> Web3.toJSON({'one': 1})
'{"one": 1}'

.. _overview_currency_conversions:

Currency Conversions
Expand Down
56 changes: 56 additions & 0 deletions tests/core/web3-module/test_conversions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@

import pytest

from hexbytes import (
HexBytes,
)

from web3 import Web3
from web3.datastructures import (
AttributeDict,
)


@pytest.mark.parametrize(
Expand Down Expand Up @@ -192,3 +199,52 @@ def test_to_hex_text(val, expected):
)
def test_to_hex_cleanup_only(val, expected):
assert Web3.toHex(hexstr=val) == expected


@pytest.mark.parametrize(
'val, expected',
(
(AttributeDict({'one': HexBytes('0x1')}), '{"one": "0x01"}'),
(AttributeDict({'two': HexBytes(2)}), '{"two": "0x02"}'),
(AttributeDict({
'three': AttributeDict({
'four': 4
})
}), '{"three": {"four": 4}}'),
({'three': 3}, '{"three": 3}'),
),
)
def test_to_json(val, expected):
assert Web3.toJSON(val) == expected


@pytest.mark.parametrize(
'tx, expected',
(
(
AttributeDict({
'blockHash': HexBytes(
'0x849044202a39ae36888481f90d62c3826bca8269c2716d7a38696b4f45e61d83'
),
'blockNumber': 6928809,
'from': '0xDEA141eF43A2fdF4e795adA55958DAf8ef5FA619',
'gas': 21000,
'gasPrice': 19110000000,
'hash': HexBytes(
'0x1ccddd19830e998d7cf4d921b19fafd5021c9d4c4ba29680b66fb535624940fc'
),
'input': '0x',
'nonce': 5522,
'r': HexBytes('0x71ef3eed6242230a219d9dc7737cb5a3a16059708ee322e96b8c5774105b9b00'),
's': HexBytes('0x48a076afe10b4e1ae82ef82b747e9be64e0bbb1cc90e173db8d53e7baba8ac46'),
'to': '0x3a84E09D30476305Eda6b2DA2a4e199E2Dd1bf79',
'transactionIndex': 8,
'v': 27,
'value': 2907000000000000
}),
'{"blockHash": "0x849044202a39ae36888481f90d62c3826bca8269c2716d7a38696b4f45e61d83", "blockNumber": 6928809, "from": "0xDEA141eF43A2fdF4e795adA55958DAf8ef5FA619", "gas": 21000, "gasPrice": 19110000000, "hash": "0x1ccddd19830e998d7cf4d921b19fafd5021c9d4c4ba29680b66fb535624940fc", "input": "0x", "nonce": 5522, "r": "0x71ef3eed6242230a219d9dc7737cb5a3a16059708ee322e96b8c5774105b9b00", "s": "0x48a076afe10b4e1ae82ef82b747e9be64e0bbb1cc90e173db8d53e7baba8ac46", "to": "0x3a84E09D30476305Eda6b2DA2a4e199E2Dd1bf79", "transactionIndex": 8, "v": 27, "value": 2907000000000000}' # noqa: E501
),
),
)
def test_to_json_with_transaction(tx, expected):
assert Web3.toJSON(tx) == expected
30 changes: 26 additions & 4 deletions web3/_utils/encoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
remove_0x_prefix,
to_hex,
)
from hexbytes import (
HexBytes,
)

from web3._utils.abi import (
is_address_type,
Expand All @@ -39,6 +42,9 @@
validate_abi_type,
validate_abi_value,
)
from web3.datastructures import (
AttributeDict,
)


def hex_encode_abi_type(abi_type, value, force_size=None):
Expand Down Expand Up @@ -238,9 +244,9 @@ def _json_list_errors(self, iterable):
except TypeError as exc:
yield "%d: because (%s)" % (index, exc)

def _friendly_json_encode(self, obj):
def _friendly_json_encode(self, obj, cls=None):
try:
encoded = json.dumps(obj)
encoded = json.dumps(obj, cls=cls)
return encoded
except TypeError as full_exception:
if hasattr(obj, 'items'):
Expand All @@ -262,9 +268,9 @@ def json_decode(self, json_str):
# so we have to re-raise the same type.
raise json.decoder.JSONDecodeError(err_msg, exc.doc, exc.pos)

def json_encode(self, obj):
def json_encode(self, obj, cls=None):
try:
return self._friendly_json_encode(obj)
return self._friendly_json_encode(obj, cls=cls)
except TypeError as exc:
raise TypeError("Could not encode to JSON: {}".format(exc))

Expand Down Expand Up @@ -309,3 +315,19 @@ def encode_single_packed(_type, value):
return codecs.encode(value, 'utf8')
elif abi_type.base == "bytes":
return value


class Web3JsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, AttributeDict):
return {k: v for k, v in obj.items()}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems like it should be a recursive operation, re-encoding each of the k and v values using json.JSONEncoder.default(self, v)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like json.JSONEncoder already handles recursion. default() just needs to provide one to one conversion. I added a test with a nested AttributeDict as verification.

if isinstance(obj, HexBytes):
return obj.hex()
return json.JSONEncoder.default(self, obj)


def to_json(obj):
'''
Convert a complex object (like a transaction object) to a JSON string
'''
return FriendlyJsonSerde().json_encode(obj, cls=Web3JsonEncoder)
2 changes: 2 additions & 0 deletions web3/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
to_hex,
to_int,
to_text,
to_json,
)
from web3._utils.normalizers import (
abi_ens_resolver,
Expand Down Expand Up @@ -117,6 +118,7 @@ class Web3:
toInt = staticmethod(to_int)
toHex = staticmethod(to_hex)
toText = staticmethod(to_text)
toJSON = staticmethod(to_json)

# Currency Utility
toWei = staticmethod(to_wei)
Expand Down