pythonsoliditysmartcontractsnsjsonserialization

solidity TypeError: Object of type set is not JSON serializable


I ran the code in VSCode and got a TypeError: Object of type set is not JSON serializable. I just start to learn to code, really don't get it, and googled it, also didn't know what does JSON serializable means.

from solcx import compile_standard
import json

# get the contract content
with open("./SimpleStorage.sol", "r") as file:
    simple_storage_file = file.read()

# compile the contract

compiled_sol = compile_standard(
    {
        "language": "Solidity",
        "sources": {"SimpleStorage.sol": {"content": simple_storage_file}},
        "settings": {
            "outputSelection": {
                "*": {
                    "*": {"abi", "metadata", "evm.bytecode", "evm.bytecode.sourceMap"}
                }
            }
        },
    },
    solc_version="0.6.0",
)

# creat json file dump the comiled code in it to make it more readable.
with open("compiled_code.json", "w") as file:
    json.dump(compiled_sol, file)

print(compiled_sol)

The full error information is below:

(env) (base) liwei@liweideMacBook-Pro practice % python3 deploy.py
Traceback (most recent call last):
  File "deploy.py", line 10, in <module>
    compiled_sol = compile_standard(
  File "/Users/liwei/Desktop/demos/practice/env/lib/python3.8/site-packages/solcx/main.py", line 375, in compile_standard
    stdin=json.dumps(input_data),
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type set is not JSON serializable

Solution

  • Instead of this:

    {"abi", "metadata", "evm.bytecode", "evm.bytecode.sourceMap"}
    

    you should use this:

    ["abi", "metadata", "evm.bytecode", "evm.bytecode.sourceMap"]
    

    Sets in Python aren't JSON serializable.