我遇到了一個非常奇怪的問題:我使用json.dump編寫文件,然後使用json.load來讀取文件。如何在mac os上使用json
相同的代碼可以運行在Windows 7上成功,但它不能在Mac OS上做X 10.7 下面是代碼:
class Result:
def __init__(self,name,result):
self.name = name
self.result = result
def __repr__(self):
return 'Result name : %s , result : %s' % (self.name,self.result)
class MyEncoder(json.JSONEncoder):
def default(self,obj):
#convert object to a dict
d = {'CaseResult':{}}
d['CaseResult'][obj.name] = obj.result
return d
def save(name,result):
filename = 'basic.json'
obj = Result(name,result)
obj_json = MyEncoder().encode(obj)
with open(filename, mode='ab+') as fp:
json.dump(obj_json,fp)
s=json.load(fp)
save('aaa','bbb')
在Mac OS它給出一個錯誤「ValueError異常:NO JSON對象可以被解碼「 誰可以告訴我爲什麼會發生這種情況,我該如何解決它
發佈您的JSON。如果同一個文件在Windows上運行,而不是在MacOS上運行,我的第一個猜測就是字符編碼問題。 – Hansi 2012-02-17 11:11:30
請張貼您的Python代碼。現在它不是有效的Python。 – 2012-02-17 11:14:00
這不是Mac OS X的問題。您的初始代碼在Ubuntu下引發相同的錯誤。 – 2012-02-17 11:14:32