Search code examples
pythonpython-3.xdata-transform

python string find and look up on string until found space from json


Below is my data.

'{"Data": {"a":5647953897,"b":"323299901059958183671030","c":1605858513465}}{"Data": {"a":5647953897,"b":"323299901059958183671030","c":1605858513465}}'

My output should be as below

[{"a":5647953897,"b":"323299901059958183671030","c":1605858513465},{"a":5647953897,"b":"323299901059958183671030","c":1605858513465}]

Solution

  • This should solve your case.

    from json import JSONDecoder, JSONDecodeError
    import re
    
    NOT_WHITESPACE = re.compile(r'[^\s]')
    
    data = '''{"Data": {"a":5647953897,"b":"323299901059958183671030","c":1605858513465}}{"Data": {"a":5647953897,"b":"323299901059958183671030","c":1605858513465}}'''
    
    def decode_stacked(document, pos=0, decoder=JSONDecoder()):
        while True:
            match = NOT_WHITESPACE.search(document, pos)
            if not match:
                return
            pos = match.start()
    
            try:
                obj, pos = decoder.raw_decode(document, pos)
            except JSONDecodeError:
                raise
            yield obj
            
    for obj in decode_stacked(data):
        print(obj)