Last active
          December 14, 2019 16:55 
        
      - 
      
- 
        Save luispfonseca/451f7082e9ecd7be2f373fee0cc6df99 to your computer and use it in GitHub Desktop. 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | #!/usr/bin/env python | |
| # coding=utf-8 | |
| ## Converte ficheiro JSON com os contratos do base no dados.gov.pt | |
| ## para um formato válido | |
| ## Não fica ainda totalmente de acordo com o Open Contracting Data Standard | |
| ## https://standard.open-contracting.org/latest/en/ | |
| ## porque não inclui os metadados na base, apenas os registos | |
| ## Problema com ficheiro original é que tem uma linha de json valido para cada contrato | |
| ## Não é JSON valido no seu conjunto | |
| ## Este código recolhe só os dados dos contratos mas não os metadados | |
| import json | |
| import os | |
| import re | |
| filepath_input = "sample_large.json" | |
| filepath_output = "base2ocds_jsonarray.json" | |
| with open(filepath_output,"w") as fo: | |
| fo.write("[") | |
| with open(filepath_input) as fp: | |
| line = fp.readline() | |
| cnt = 0 | |
| while line: | |
| print(cnt) | |
| # em cada linha, extrair os records com regex | |
| records = re.findall('"records.*\n', line) | |
| if len(records) > 0: | |
| records = records[0] | |
| records = re.sub('"records":\[',"",records,count=1) | |
| records = records[:-4] | |
| with open(filepath_output,"a") as fo: | |
| fo.write(records + ",") | |
| cnt += 1 | |
| line = fp.readline() | |
| with open(filepath_output, 'rb+') as filehandle: | |
| filehandle.seek(-1, os.SEEK_END) | |
| filehandle.truncate() | |
| with open(filepath_output,"a") as fo: | |
| fo.write("]") | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment