본문 바로가기
python

python json file read & write

by dyyoo 2019. 4. 10.

파이썬 json 파일 읽기 쓰기.

 

rest server에서 array of json 데이터를 받아서 관리하려는데, 간단하게 파일로 저장함

 

json 모듈을 쓰고

 

경로는 기본으로

 

readJson(), readJson2()는 같은기능.

 

# 아래는 example data

persons = \
[
  {
    'name': "John",
    "isAlive": True,
    "age": 20,
    "address": {
      "streetAddress": "22 2nd Street",
      "city": "New York",
  }
},
  {
    'name': "Bob",
    "isAlive": True,
    "age": 30,
    "address": {
      "streetAddress": "240 O Conner Street",
      "city": " Ocean Springs",
  }
}
]

 

def readJson():
  try:
    data = open('p_list.json', 'r').read()
    print(data)

    return json.loads(data)
  except Exception as e:
    print(e)

 

def readJson2():
  try:
    with open('p_list.json', 'r') as f:
    person = json.load(f)
    return person

  except Exception as e:
    print(e)

 

def writeJson():
  try:
    with open('p_list.json', 'w') as f:
    json.dump(persons, f)
  except Exception as e:
    print(e)

 

#main
writeJson()
read1 = readJson()
read2 = readJson2()

'python' 카테고리의 다른 글

h5 파일 생성, 읽기  (0) 2019.04.17

댓글