2014-02-05 33 views
2

我正在加載一個json文件並嘗試拉出一些值,然後按行輸出該組值。在新行上輸出一組json對象而不是單行

電流輸出看起來是這樣的:

{"time":"1:2:2","post":"1","user":"4","text":"Masaru Emoto"}{"time":"1:3:8","post":"8","user":"5","text":"Meteors"}{"time":"7:4:5","post":"1","user":"8","text":"Olympics"} 

而且我希望它看起來像這樣:

{"time":"1:2:2","post":"1","user":"4","text":"Masaru Emoto"} 
{"time":"1:3:8","post":"8","user":"5","text":"Meteors"} 
{"time":"7:4:5","post":"1","user":"8","text":"Olympics"} 

我想不通的地方添加「\ n」來解決輸出。先謝謝您的幫助。

代碼:

import json 

json_data = open('somefile.json', 'r+').read().decode("utf-8") 
jdata = json.loads(json_data) 

def id_generator(d):  

with open('formatted_file' + '.json', 'w') as outfile: 
    for k, v in d.items(): 
     if isinstance(v, dict): 
      id_generator(v)      
     if isinstance(v, list):    
      for post in v: 
       formated = {"time":post.get('created_time'),"user":post['from']['id'], 
           "post":post.get('id'),"text":post.get('description')}           
       out = json.dumps(formated, separators=(',', ':'))               
       outfile.write(out)           
if __name__ == '__main__': 
    try: 
     id_generator(jdata) 
    except TypeError: 
     pass 
+1

'outfile.write(out +'\ n')'? –

+0

我看不到_current output_和_look就像this_輸出中的任何區別。 – JamesThomasMoon1979

+0

@ JamesThomasMoon1979我想有人編輯它,它最初不會添加換行符,所以輸出是單個字符串。 – user2338089

回答

7

的格式化有點打破了你的消息,但我相信你想每次寫調用(每個職位)後換行符。

只要做outfile.write(out + '\n')。在給定的系統上,\n將被自動轉換爲適當的行分隔符。

+0

釘釘了!我每次都會在格式化的時候提出一個問題。謝謝您的幫助。 – user2338089

相關問題