"""Run the reading examples in order from this folder."""

import json

with open('tweets.json', encoding='utf-8') as f:
    jsontext = f.read()

data = json.loads(jsontext)
print(type(data))
print(data[0])
print(data[0]['username'])

print(sum(1 for tweet in data if tweet['username'] == 'Obama'))

with open('tweets.json', encoding='utf-8') as f:
    data = json.load(f)

with open('tweets.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, indent=2)

config = {'title': 'My Blog', 'port': 8080, 'debug': True, 'tags': ['python', 'web']}
print(json.dumps(config, indent=2))

print(json.dumps(data, indent=2))

with open('config.json', 'w', encoding='utf-8') as f:
    json.dump(config, f, indent=2)

print(json.dumps({'author': None}))

response = {'choices': [{'message': {'content': 'Two tweets are from Obama.'}}]}
reply = response['choices'][0]['message']['content']
print(reply)

import yaml

with open('config.yaml', encoding='utf-8') as f:
    config = yaml.safe_load(f)
print(config)

print(yaml.safe_load('country: no'))

print(yaml.safe_load('on: push'))
print(yaml.safe_load('"on": push'))
print(yaml.safe_load('version: 3.10'))
print(yaml.safe_load('version: "3.10"'))

messages = yaml.safe_load("""
welcome: |
  Hello!
  Welcome to the blog.
summary: >
  Posts from
  this week.
""")
print(repr(messages['welcome']))
print(repr(messages['summary']))


import tomllib

with open('config.toml', 'rb') as f:
    config = tomllib.load(f)
print(config)

settings = tomllib.loads('''
[owner]
name = "Ada"

[export.csv]
columns = ["username", "text"]
options = {header = true, delimiter = ","}
''')
print(settings['owner']['name'])
print(settings['export']['csv']['columns'][0])
print(settings['export']['csv']['options']['header'])

import csv

with open('tweets.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.DictWriter(f, fieldnames=['text', 'username'])
    writer.writeheader()
    writer.writerows(data)

with open('tweets.csv', newline='', encoding='utf-8') as f:
    for row in csv.DictReader(f):
        print(row)

import io

csv_buffer = io.StringIO()
writer = csv.DictWriter(csv_buffer, fieldnames=['text', 'username'],
                        lineterminator='\n')
writer.writeheader()
writer.writerow(data[0])
csv_text = csv_buffer.getvalue()
print(csv_text, end='')
print(list(csv.DictReader(io.StringIO(csv_text))))
