fork(2) download
  1. import json
  2.  
  3. def RawJSONDecoder(index):
  4. class _RawJSONDecoder(json.JSONDecoder):
  5. end = None
  6.  
  7. def decode(self, s, *_):
  8. data, self.__class__.end = self.raw_decode(s, index)
  9. return data
  10. return _RawJSONDecoder
  11.  
  12. def extract_json(s, index=0):
  13. while (index := s.find('{', index)) != -1:
  14. try:
  15. yield json.loads(s, cls=(decoder := RawJSONDecoder(index)))
  16. index = decoder.end
  17. except json.JSONDecodeError:
  18. index += 1
  19.  
  20. s = '''...some {{bad brackets} and empty brackets {} <= still valid JSON though...
  21.  
  22. {
  23. "1":"one",
  24. "2":"two",
  25. "3":{
  26. "31":{
  27. "311":"threeoneone",
  28. "312":"threeonetwo",
  29. "313":"threeonethree"
  30. }
  31. },
  32. "4":{
  33. "41":"fourone",
  34. "42":"fourtwo",
  35. "43":"fourthree"
  36. },
  37. "5":"five",
  38. "6":"six"
  39. }
  40.  
  41. ...some more random text...'''
  42. print(*extract_json(s), sep='\n')
Success #stdin #stdout 0.03s 9816KB
stdin
Standard input is empty
stdout
{}
{'1': 'one', '2': 'two', '3': {'31': {'311': 'threeoneone', '312': 'threeonetwo', '313': 'threeonethree'}}, '4': {'41': 'fourone', '42': 'fourtwo', '43': 'fourthree'}, '5': 'five', '6': 'six'}