JSON をファイルに保存およびファイルから読み込むには、open file オブジェクトを使用します。あなたのコードは、ファイルself.data
オブジェクトではないファイル名をに保存しようとしたことを示しています...
次のコードが機能します。
def write(self, filename):
with open(filename, 'w') as output:
json.dump(self.data, output)
def load(self, filename):
with open(filename, 'r') as input:
self.data = json.load(input)
開いているファイルをコンテキスト マネージャーとして使用して、読み取りまたは書き込みが完了したときにファイルが閉じられるようにします。
もう 1 つの試みは、 JSON ではなくprint >> file, self.data
、単にPython 表現をファイルに出力するだけです。
>>> print example
{u'server': {u'uid': u'uid_Sample', u'keyword': u'kwd_Sample', u'ipaddress': u'IP_Sample', u'start_time': u'start_Sample', u'label': u'label_Sample', u'stop_time': u'stop_Sample', u'type': u'type_Sample', u'name': u'name_Sample'}}
ファイルから読み返すと、指定したエラーメッセージが表示されます。
>>> json.loads("{u'server': {u'uid': u'uid_Sample', u'keyword': u'kwd_Sample', u'ipaddress': u'IP_Sample', u'start_time': u'start_Sample', u'label': u'label_Sample', u'stop_time': u'stop_Sample', u'type': u'type_Sample', u'name': u'name_Sample'}}")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/__init__.py", line 307, in loads
return _default_decoder.decode(s)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/decoder.py", line 319, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/decoder.py", line 336, in raw_decode
obj, end = self._scanner.iterscan(s, **kw).next()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/scanner.py", line 55, in iterscan
rval, next_pos = action(m, context)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/decoder.py", line 171, in JSONObject
raise ValueError(errmsg("Expecting property name", s, end))
ValueError: Expecting property name: line 1 column 1 (char 1)
json.dumps()
代わりに出力を印刷する必要があります。
>>> print json.dumps(example)
'{"server": {"uid": "uid_Sample", "keyword": "kwd_Sample", "ipaddress": "IP_Sample", "start_time": "start_Sample", "label": "label_Sample", "stop_time": "stop_Sample", "type": "type_Sample", "name": "name_Sample"}}'