레이블이 python인 게시물을 표시합니다. 모든 게시물 표시
레이블이 python인 게시물을 표시합니다. 모든 게시물 표시

2013년 9월 2일 월요일

python json dict 변경시 에러 발생

python에서 json string을 dict로 변경하려는데 아래와 같은 에러가 발생했다.

ValueError: Extra data: line 1 column 316 - line 1 column 320 (char 316 - 320)

원인은 json string 의 마지막에 \0x00 이란 문자열이 뒤에 붙어 있어서 였다.


<example>

#!/usr/bin/python
# -*- coding:utf-8 -*-

import json, simplejson

# 문자열에 \x00이 있다고 가정
str = '{"json_key":"json_value"}\x00'

# \x00 으로 에러가 발생할 것이다.
print json.loads(str)

>>>>
Traceback (most recent call last):
  File "a.py", line 10, in <module>
    print json.loads(str)
  File "/usr/lib64/python2.6/json/__init__.py", line 307, in loads
    return _default_decoder.decode(s)
  File "/usr/lib64/python2.6/json/decoder.py", line 322, in decode
    raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 1 column 25 - line 1 column 26 (char 25 - 26)





#!/usr/bin/python
# -*- coding:utf-8 -*-

import json, simplejson

# print 로 확인하면 보이지 않아 repr로 확인해 보면\x00 이 보일 것이다.
str = '{"json_key":"json_value"}\x00'
print repr(str)

>>>
'{"json_key":"json_value"}\x00'





#!/usr/bin/python
# -*- coding:utf-8 -*-

import json, simplejson

# 0x00이 들어간 것을 치환하여 dict로 변환하자
str = '{"json_key":"json_value"}\x00'
str = str.replace('\x00', '')

# 0x00을 빈문자로 치환하여 변환하면 정상적으로 변환이 될 것이다.
print json.loads(str)
>>>
{u'json_key': u'json_value'}