2011-09-11 24 views
0

我見,我認爲以下JSON(簡化這個例子):如何外部化JSON

video = 
    { 
    'label': 'hd', 
    'url': 'google', 
    'format': 'mp4', 
    'video_codec': 'h264', 
    'audio_codec': 'aac', 
    'size': '1080x720', 
    } 

而且我可以調用像這樣的功能:do_something(視頻)

然而,當我嘗試並提取該JSON到外部文件,內容如下 -

file=open('data.json') 
video=file.read() 

我得到一個錯誤,這似乎涉及到具有文件中換行符和過多的空間。我將如何1)格式化上述json文件,將其放入外部文件中;和2)我將如何導入它,所以我可以使用它的功能?謝謝。

+2

Arggh!單引號是不合法的JSON! –

+1

也不是任務。 –

+0

是第一個代碼塊的文件內容,還是有別的東西?你能發佈實際的錯誤信息嗎? – SingleNegationElimination

回答

4

一旦您擁有實際的JSON,最好從json.dump()開始,這很容易。

$ cat t.json 
{ 
    "label": "hd", 
    "url": "google", 
    "format": "mp4", 
    "video_codec": "h264", 
    "audio_codec": "aac", 
    "size": "1080x720" 
} 
$ python << EOF 
> import json 
> f = open('t.json') 
> print json.load(f) 
> f.close() 
> EOF 
{u'format': u'mp4', u'url': u'google', u'label': u'hd', u'audio_codec': u'aac', u'video_codec': u'h264', u'size': u'1080x720'}