AWS Athena export array of structs to JSON

后端 未结 2 1728
面向向阳花
面向向阳花 2021-02-12 19:39

I\'ve got an Athena table where some fields have a fairly complex nested format. The backing records in S3 are JSON. Along these lines (but we have several more levels of nest

2条回答
  •  孤城傲影
    2021-02-12 20:01

    The python code from @tarun almost got me there, but I had to modify it in several ways due to my data. In particular, I have:

    • json structures saved in Athena as strings
    • Strings that contain multiple words, and therefore need to be in between double quotes. Some of them contain "[]" and "{}" symbols.

    Here is the code that worked for me, hopefully will be useful for others:

    #!/usr/bin/env python
    import io
    import re, sys
    
    pattern1 = re.compile(r'(?<={)([a-z]+)=', re.I)
    pattern2 = re.compile(r':([a-z][^,{}. [\]]+)', re.I)
    pattern3 = re.compile(r'\\"', re.I)
    
    with io.open(sys.argv[1]) as f:
        headers = list(map(lambda f: f.strip(), f.readline().split(",")))
        print(headers)
        for line in f.readlines():
    
            orig_line = line
            #save the double quote cases, which mean there is a string with quotes inside
            line = re.sub('""', "#", orig_line)
            data = []
            for i, l in enumerate(line.split('","')):
                item = re.sub('^"|"$', "", l.rstrip())
                if (item[0] == "{" and item[-1] == "}") or (item[0] == "[" and item[-1] == "]"):
                    data.append(headers[i] + ":" + item)
                else: #we have a string
                    data.append(headers[i] + ": \"" + item + "\"")
    
            line = "{" + ','.join(data) + "}"
            line = pattern1.sub(r'"\1":', line)
            line = pattern2.sub(r':"\1"', line)
    
            #restate the double quotes to single ones, once inside the json
            line = re.sub("#", '"', line)
    
            print(line)
    

提交回复
热议问题