【Python】jsonのsort_keys

json.dumpする際に、sort_keysをTrueとすることで、dictionallyのkeyでソートする

import json
class MyClass:
    def __init__(self, a, c, b):
        self.a = a
        self.c = c
        self.b = b

obj = MyClass(2, 4, 6)

string = json.dumps(obj.__dict__)
print(string)

string = json.dumps(obj.__dict__, sort_keys=True)
print(string)

$ python3 test.py
{“a”: 2, “c”: 4, “b”: 6}
{“a”: 2, “b”: 6, “c”: 4}

なるほど、これで下のコードが何をやってるのか理解できたわ

import hashlib
import json
from datetime import datetime
import random

class Block:
    def __init__(self, index, previous_hash, timestamp, data, validator):
        self.index = index
        self.previous_hash = previous_hash
        self.timestamp = timestamp
        self.data = data
        self.validator = validator
        self.hash = self.calculate_hash()

    def calculate_hash(self):
        block_dict = self.__dict__
        if 'hash' in block_dict:
            del block_dict['hash']
        block_string = json.dumps(block_dict, sort_keys=True).encode()
        return hashlib.sha256(block_string).hexdigest()