상세 컨텐츠

본문 제목

xml, json

Python

by techbard 2025. 4. 24. 11:15

본문

반응형

 

### remote internet json data 가져오기 ###

# -*- encoding: utf-8 -*-
import sys, io
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')

import requests, pprint

url = "https://restcountries.com/v3.1/all"
response = requests.get(url)
countrys = response.json()

find_country = "Iceland"
for c in countrys:
    c_name = c['name']['common']
    if c_name in find_country:
        pprint.pp(c)

###output
# {'name': {'common': 'Iceland',
          # 'official': 'Iceland',
          # 'nativeName': {'isl': {'official': 'Ísland', 'common': 'Ísland'}}},
 # 'tld': ['.is'],
 # 'cca2': 'IS',
 # 'ccn3': '352',
 # 'cca3': 'ISL',
 # 'cioc': 'ISL',
 # 'independent': True,
 # 'status': 'officially-assigned',
 # 'unMember': True,
 # 'currencies': {'ISK': {'name': 'Icelandic króna', 'symbol': 'kr'}},
 # 'idd': {'root': '+3', 'suffixes': ['54']},
 # 'capital': ['Reykjavik'],
 # 'altSpellings': ['IS', 'Island', 'Republic of Iceland', 'Lýðveldið Ísland'],
 # 'region': 'Europe',
 # 'subregion': 'Northern Europe',
 # 'languages': {'isl': 'Icelandic'},
 # 'translations': {'ara': {'official': 'آيسلندا', 'common': 'آيسلندا'},
                  # 'bre': {'official': 'Island', 'common': 'Island'},
                  # 'ces': {'official': 'Island', 'common': 'Island'},
                  # 'cym': {'official': 'Iceland', 'common': 'Iceland'},
                  # 'deu': {'official': 'Island', 'common': 'Island'},
                  # 'est': {'official': 'Islandi Vabariik', 'common': 'Island'},
                  # 'fin': {'official': 'Islanti', 'common': 'Islanti'},
                  # 'fra': {'official': "République d'Islande",
                          # 'common': 'Islande'},
                  # 'hrv': {'official': 'Island', 'common': 'Island'},
                  # 'hun': {'official': 'Izland', 'common': 'Izland'},
                  # 'ita': {'official': 'Islanda', 'common': 'Islanda'},
                  # 'jpn': {'official': 'アイスランド', 'common': 'アイスランド'},
                  # 'kor': {'official': '아이슬란드 공화국', 'common': '아이슬란드'},
                  # 'nld': {'official': 'IJsland', 'common': 'IJsland'},
                  # 'per': {'official': 'جمهوری ایسلند', 'common': 'ایسلند'},
                  # 'pol': {'official': 'Republika Islandii',
                          # 'common': 'Islandia'},
                  # 'por': {'official': 'Islândia', 'common': 'Islândia'},
                  # 'rus': {'official': 'Исландия', 'common': 'Исландия'},
                  # 'slk': {'official': 'Islandská republika',
                          # 'common': 'Island'},
                  # 'spa': {'official': 'Islandia', 'common': 'Islandia'},
                  # 'srp': {'official': 'Исланд', 'common': 'Исланд'},
                  # 'swe': {'official': 'Island', 'common': 'Island'},
                  # 'tur': {'official': 'İzlanda', 'common': 'İzlanda'},
                  # 'urd': {'official': 'آئس لینڈ', 'common': 'آئس لینڈ'},
                  # 'zho': {'official': '冰岛', 'common': '冰岛'}},
 # 'latlng': [65.0, -18.0],
 # 'landlocked': False,
 # 'area': 103000.0,
 # 'demonyms': {'eng': {'f': 'Icelander', 'm': 'Icelander'},
              # 'fra': {'f': 'Islandaise', 'm': 'Islandais'}},
 # 'flag': '🇮🇸',
 # 'maps': {'googleMaps': 'https://goo.gl/maps/WxFWSQuc3oamNxoE6',
          # 'openStreetMaps': 'https://www.openstreetmap.org/relation/299133'},
 # 'population': 366425,
 # 'gini': {'2017': 26.1},
 # 'fifa': 'ISL',
 # 'car': {'signs': ['IS'], 'side': 'right'},
 # 'timezones': ['UTC'],
 # 'continents': ['Europe'],
 # 'flags': {'png': 'https://flagcdn.com/w320/is.png',
           # 'svg': 'https://flagcdn.com/is.svg',
           # 'alt': 'The flag of Iceland has a blue field with a large '
                  # 'white-edged red cross that extends to the edges of the '
                  # 'field. The vertical part of this cross is offset towards '
                  # 'the hoist side.'},
 # 'coatOfArms': {'png': 'https://mainfacts.com/media/images/coats_of_arms/is.png',
                # 'svg': 'https://mainfacts.com/media/images/coats_of_arms/is.svg'},
 # 'startOfWeek': 'monday',
 # 'capitalInfo': {'latlng': [64.15, -21.95]},
 # 'postalCode': {'format': '###', 'regex': '^(\\d{3})$'}}

 

### remote internet json data 가져오기 ###

# -*- encoding: utf-8 -*-
import sys, io
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')

# import requests
import pprint, json, os

# url = "https://restcountries.com/v3.1/all"
# response = requests.get(url)
# countrys = response.json()

def json_read():
    file_path = os.path.join("C:/Users/SKTelecom/UserApps/PyScripter/MyPrj/2024-11-07", "all_countries.json")
    with open(file_path, "r", encoding="UTF-8") as f:
        return json.load(f)

def find_capital(country_data):
    find = (input("Enter country: ")).lower()
    for c in country_data:
        country_name = (c['name']['common']).lower()
        if find in country_name:
            print(c['capital'][0])

c_data = json_read()
find_capital(c_data)

###output
Enter country: greece
Athens

 

 

 

 

 

 

 

# xml generator

 

from xml.etree.ElementTree import Element, SubElement, tostring

 

root = Element('rebels')

rebel = SubElement(root, 'rebel')

 

firstName = SubElement(rebel, 'firstName')

lastName = SubElement(rebel, 'lastName')

 

firstName.text = 'Luke'

lastName.text = 'Skywalker'

 

print(tostring(root))

 

# 결과

b'<rebels><rebel><firstName>Luke</firstName><lastName>Skywalker</lastName></rebel></rebels>'

 

# json generator

 

import json

 

straightJSON = json.dumps(['rebles', 

{'firstName': 'Luke', 'lastName': 'Skywalker'}],

separators = (',', ':'))

 

print("straightJSON Output:\n", straightJSON)

 

prettyJSON = json.dumps(['rebels',

{'firstName': 'Luke', 'lastName': 'Skywalker'}],

sort_keys=True,

indent = 4)

 

print("preetyJSON Output:\n", prettyJSON)

 

# 결과

straightJSON Output:

 ["rebles",{"firstName":"Luke","lastName":"Skywalker"}]

preetyJSON Output:

 [

    "rebels",

    {

        "firstName": "Luke",

        "lastName": "Skywalker"

    }

]

 

import json, pprint

a_string = '\n\n\n{\n "resultCount":25,\n "results": [\n{"wrapperType":"track", "kind":"podcast", "collectionId":10892}]}'
print(a_string)

d = json.loads(a_string)
print("==========" * 7)
print(type(d))
print(d.keys())
print(d['resultCount'])
print(d['results'][0]['wrapperType'])
print("")
pprint.pp(d)

###output
##{'resultCount': 25,
## 'results': [{'wrapperType': 'track',
##              'kind': 'podcast',
##              'collectionId': 10892}]}
반응형

관련글 더보기

댓글 영역