Last active
April 6, 2023 04:41
-
-
Save rg3915/51eab9cba81f7d422df390e61d5e338f to your computer and use it in GitHub Desktop.
desafio 4 - agrupar dados de um JSON - agrupar pela data
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
function group_by_date(transactions) { | |
/* | |
Agrupa os dados por data. | |
*/ | |
// Dicionário vazio | |
const result = {} | |
for (const transaction of transactions) { | |
// Adiciona uma chave no dicionário | |
const date = transaction['date'] | |
if (date in result) { | |
// Adiciona numa lista | |
result[date].push(transaction) | |
} else { | |
// Adiciona uma nova chave de data. | |
result[date] = [transaction] | |
} | |
} | |
return result | |
} |
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
import json | |
import requests | |
def get_data(url): | |
''' | |
Usando lib requests, pega os dados direto da url fornecida. | |
''' | |
response = requests.get(url) | |
if response.status_code != 200: | |
return | |
content = response.content.decode('utf-8') | |
# Remove a última vírgula | |
content = content[:-4] + content[-3:] | |
# Remove ponto e virgula | |
content = content.rstrip(';') | |
# Pega o conteúdo e transforma aspas simples em aspas duplas. | |
content = content.replace("'", '"') | |
# Adiciona aspas duplas nas chaves | |
content = content.replace('date', '"date"') | |
content = content.replace('description', '"description"') | |
content = content.replace('amount', '"amount"') | |
data = json.loads(content) | |
return data | |
def group_by_date(transactions): | |
''' | |
Agrupa os dados por data. | |
''' | |
# Dicionário vazio | |
result = {} | |
for transaction in transactions: | |
# Adiciona uma chave no dicionário | |
date = transaction['date'] | |
if date in result: | |
# Adiciona numa lista | |
result[date].append(transaction) | |
else: | |
# Adiciona uma nova chave de data. | |
result[date] = [transaction] | |
return result | |
if __name__ == '__main__': | |
URL = 'https://gist.githubusercontent.com/tiagomatosweb/2f1ba06bde77926fb35eb09da7e77598/raw/506c8e6bf499a80a43d4ebdf60a5e8c7b5a5d4d4/transactions.js' | |
transactions = get_data(URL) | |
print(transactions) | |
result = group_by_date(transactions) | |
print(json.dumps(result, indent=4)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment