2016-02-26 25 views
0

我有一個json數組。並且需要使用python打印唯一的id。我該怎麼做?如何使用python打印完整的json數組?

這是我的JSON數組:

{ 
"messages": 
    [ 
    { 

    "id": "1531cf7d9e03e527", 
    "threadId": "1531cf7d9e03e527" 
    }, 

    { 
    "id": "1531cdafbcb4a0e6", 
    "threadId": "1531bfccfceb1ed7" 
    } 

], 

"nextPageToken": "01647645424797380808", 

"resultSizeEstimate": 103 
} 

*編輯:*

其實我寫的Python代碼從Gmail的API消息。 該程序將消息的id和gmail帳戶消息的線程標識作爲json格式給出。我只需要消息ID而不是線程ID。

from __future__ import print_function 
import httplib2 
import os 

from apiclient import discovery 
import oauth2client 
from oauth2client import client 
from oauth2client import tools 
import json 
try: 
    import argparse 
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() 
    except ImportError: 
    flags = None 


SCOPES = 'https://www.googleapis.com/auth/gmail.readonly' 
CLIENT_SECRET_FILE = 'client_server.json' 
APPLICATION_NAME = 'Gmail API Python Quickstart' 

def get_credentials(): 

    home_dir = os.path.expanduser('~') 
    credential_dir = os.path.join(home_dir, '.credentials') 
    if not os.path.exists(credential_dir): 
     os.makedirs(credential_dir) 
    credential_path = os.path.join(credential_dir, 
            'gmail-python-quickstart.json') 

    store = oauth2client.file.Storage(credential_path) 
    credentials = store.get() 
    if not credentials or credentials.invalid: 
     flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) 
     flow.user_agent = APPLICATION_NAME 
     if flags: 
      credentials = tools.run_flow(flow, store, flags) 
     else: 
      credentials = tools.run(flow, store) 
     print('Storing credentials to ' + credential_path) 
    return credentials 
def main(): 

    credentials = get_credentials() 
    http = credentials.authorize(httplib2.Http()) 
    service = discovery.build('gmail', 'v1', http=http) 
    message = service.users().messages().get(userId='me',id='').execute() 
    response = service.users().messages().list(userId='me',q='').execute() 
    messages = [] 
    if 'messages' in response: 
     messages.extend(response['messages']) 
     print(messages) 

    result = loads(messages) 
    ids = [message['id'] for message in result['messages']] 
    print (ids) 

    while 'nextPageToken' in response: 
     page_token = response['nextPageToken'] 
     response = service.users().messages().list(userId='me', q='',pageToken=page_token).execute() 
     messages.extend(response['messages']) 
    print(message['id']) 

    print (message['snippet']) 



if __name__ == '__main__': 
    main() 

回答

2
import json 
dict_result = json.loads(your_json) 
ids = [message['id'] for message in dict_result['messages']] 
+0

TypeError:期望的字符串或緩衝區..它給了我raw_decode()錯誤@andrey – Indhuja

+0

看來你通過python列表而不是JSON字符串(就像你在回答中說的)。 如果是這樣,只需跳過json.loads的一部分,並在列表中創建列表迭代器。 'your_parsed_json ['messages']]中的[message ['id']消息'' –

1

因爲我沒有足夠的信譽分置評,我張貼此作爲一個答案,否則安德烈Rusanov的答案几乎是正確的。

所以,我複製你張貼的JSON和一個叫messages.json文件保存它

{ "messages": [ 
     {"id": "1531cf7d9e03e527", "threadId": "1531cf7d9e03e527" }, 
     { "id": "1531cdafbcb4a0e6", "threadId": "1531bfccfceb1ed7" } 
    ], 
    "nextPageToken": "01647645424797380808", 
    "resultSizeEstimate": 103 
} 

現在,只打印的ID:

from json import load 
result = load(open("messages.json")) 
ids = [message['id'] for message in result['messages']] 

如果你的json不在文件中並且可作爲字符串使用,

from json import loads 
json_string = """ 
{ "messages": [ 
     {"id": "1531cf7d9e03e527", "threadId": "1531cf7d9e03e527" }, 
     { "id": "1531cdafbcb4a0e6", "threadId": "1531bfccfceb1ed7" } 
    ], 
    "nextPageToken": "01647645424797380808", 
    "resultSizeEstimate": 103 
} 
""" 
result = loads(json_string) 
ids = [message['id'] for message in result['messages']] 
+0

'爲什麼我的答案几乎是正確的?你剛剛添加了一種方法來從文件中加載JSON,這不在答案的範圍內,實際上是 –

+0

@AndreyRusanov因爲他可能將一個文件傳遞給loads方法,因此得到他提到的TypeError。另外,他沒有提到他是傳遞一個字符串還是一個文件。這就是爲什麼我提到你的答案几乎是正確的。 –

+0

@PallabPain NameError:全局名稱'loads'未定義是我得到的錯誤!但我確實有導入json聲明! – Indhuja

1
messages=[] 
store=[] 
if 'messages' in response: 
messages.extend(response['messages']) 
for i in range(len(messages)): 
//to store the id alone (Taking the id from the json array) 
store=messages[i]['id'] 
//retrieve messages of this id 
message = service.users().messages().get(userId='me',id=store).execute() 
print(store) 
+0

請在您提出的解決方案中添加一些說明。 – Zulan