python中的Google People API给出错误:接收到无效的JSON有效负载。未知名称“”:根元素必须是一条消息。”

时间:2019-08-17 17:30:43

标签: python json google-api google-people

我正在尝试使用People API更新Google联系人。不幸的是我遇到一个错误:

收到无效的JSON有效负载。未知名称“”:根元素必须是一条消息。

执行请求时。有人有任何提示我该如何解决? JSON本身似乎还可以,因为我使用https://developers.google.com/people/api/rest/v1/people/updateContact对其进行了测试,并且得到了200条响应,并且联系人已被修改。

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request


# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/contacts']

def modifyContact(service, resourceName, JSON):
    print (JSON)
    service.people().updateContact(resourceName=resourceName, updatePersonFields='phoneNumbers', body=JSON).execute()

def buildJSON(phoneNumbers, etag):
    JSON = ""
    for x in range(0, len(phoneNumbers)):
        if phoneNumbers[x].get('type') == 'mobile':
            if phoneNumbers[x].get('value').find('+48') != -1:
                oldNUmber = phoneNumbers[x].get('value')
                newNumber = phoneNumbers[x].get('value')[3:]
                JSON += """
                        {
                            "type": "mobile",
                            "value": "%s"
                        },
                        {
                            "type": "mobile",
                            "value": "%s"
                        },
                        """ % (oldNUmber, newNumber)
            else:
                JSON += """
                        {
                            "type": "mobile",
                            "value": "%s"
                        },
                        """ % (phoneNumbers[x].get('value'))
        else:
            JSON += """
                        {
                          "type": "%s",
                            "value": "%s"
                        },
                    """ % (phoneNumbers[x].get('type'), phoneNumbers[x].get('value'))
    # remove last whitespaces + character which is exceeding comma
    JSON = JSON.rstrip()[:-1]
    JSON = """
              "phoneNumbers": [
                %s
              ],
              "etag": "%s"
            """ % (JSON, etag)
    #print (JSON)
    return JSON

def main():

    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('people', 'v1', credentials=creds)





    # Call the People API
    print('List 10 connection names')
    results = service.people().connections().list(
        resourceName='people/me',
        pageSize=1000,
        personFields='names,phoneNumbers').execute()
    connections = results.get('connections', [])

    for person in connections:
        names = person.get('names', [])
        phoneNumbers = person.get('phoneNumbers', [])
        if names:
            name = names[0].get('givenName')
            if name == "testAPI":
                print(name)
                print (person.get('etag'))
                print (person.get('resourceName'))
                if phoneNumbers:
                    JSON = buildJSON(phoneNumbers, person.get('etag'))
                    modifyContact(service, person.get('resourceName'), JSON)
                    #print (phoneNumbers[x].get('value'))
                print (person)
if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:1)

问题解决了。

首先,在进行故障排除时,我已经从JSON字符串中删除了开头/结尾的括号。

应该是:

JSON = """{
          "phoneNumbers": [
            %s
          ],
          "etag": "%s"
      }
    """ % (JSON, etag)

第二,我必须使用load()反序列化JSON字符串

return json.loads(JSON)

现在它就像一个魅力:)