721_json.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. a = {
  2. 'a': 1,
  3. 'b': 2,
  4. 'c': None,
  5. 'd': [1, 2, 3],
  6. 'e': {
  7. 'a': 100,
  8. 'b': 2.5,
  9. 'c': None,
  10. 'd': [142, 2785, 39767],
  11. },
  12. "f": 'This is a string',
  13. 'g': [True, False, None],
  14. 'h': False
  15. }
  16. import json
  17. assert json.loads("1") == 1
  18. assert json.loads('"1"') == "1"
  19. assert json.loads("0.0") == 0.0
  20. assert json.loads("[1, 2]") == [1, 2]
  21. assert json.loads("null") == None
  22. assert json.loads("true") == True
  23. assert json.loads("false") == False
  24. assert json.loads("{}") == {}
  25. # assert json.loads(b"false") == False
  26. _j = json.dumps(a)
  27. _a = json.loads(_j)
  28. for k, v in a.items():
  29. assert (a[k] == _a[k]), f'{a[k]} != {_a[k]}'
  30. for k, v in _a.items():
  31. assert (a[k] == _a[k]), f'{a[k]} != {_a[k]}'
  32. b = [1, 2, True, None, False]
  33. _j = json.dumps(b)
  34. _b = json.loads(_j)
  35. assert b == _b
  36. c = 1.0
  37. _j = json.dumps(c)
  38. _c = json.loads(_j)
  39. assert c == _c
  40. d = True
  41. _j = json.dumps(d)
  42. _d = json.loads(_j)
  43. assert d == _d
  44. assert repr((1,)) == '(1,)'
  45. assert repr((1, 2, 3)) == '(1, 2, 3)'
  46. assert repr(tuple()) == '()'
  47. assert json.dumps((1,)) == '[1]'
  48. assert json.dumps((1, 2, 3)) == '[1, 2, 3]'
  49. assert json.dumps(tuple()) == '[]'
  50. assert repr([]) == '[]'
  51. assert repr([1, 2, 3]) == '[1, 2, 3]'
  52. assert repr([1]) == '[1]'
  53. assert json.dumps([]) == '[]'
  54. assert json.dumps([1, 2, 3]) == '[1, 2, 3]'
  55. assert json.dumps([1]) == '[1]'
  56. try:
  57. json.dumps({1: 2})
  58. assert False
  59. except TypeError:
  60. assert True
  61. try:
  62. json.dumps(type)
  63. assert False
  64. except TypeError:
  65. assert True
  66. class A:
  67. def __init__(self, a, b):
  68. self.a = a
  69. self.b = b
  70. a = A(1, ['2', False, None])
  71. assert json.dumps(a.__dict__) in [
  72. '{"a": 1, "b": ["2", false, null]}',
  73. '{"b": ["2", false, null], "a": 1}',
  74. ]