You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用OpenTripPlanner API时DateTime参数引发JSON格式错误求助

OpenTripPlanner GraphQL API 日期时间参数报错解决

问题场景

使用OpenTripPlanner的transmodel/v3 GraphQL API查询行程时,带dateTime参数的请求持续报错,不带该参数的请求可正常获取响应。尝试过转义字符串、格式化传参等方式,均未解决,不确定dateTime是否需特殊对象传递。

错误信息

Unexpected character ('2' (code 50)): was expecting comma to separate Object entries
at [Source: REDACTED (StreamReadFeature.INCLUDE_SOURCE_IN_LOCATION disabled); line: 1, column: 167]

现有代码

headers = {
    'Content-Type': 'application/json',
    'OTPTimeout': '180000',
}

data2 = '{"query" :"query {trip(from: {coordinates: {latitude:  27.94942 longitude:  -82.47202 }}to:\
      {coordinates: {latitude: 27.99107 longitude: -82.45619 }} dateTime: "2024-11-18T14:00:00.000Z") \
        {tripPatterns {duration distance legs{ distance duration id mode}}}}"}'
           

response = requests.post('http://localhost:8080/otp/transmodel/v3', headers = headers, data = data2)

json_string = response.text

问题原因

核心是JSON嵌套字符串的引号转义错误:

  • 外层JSON用双引号包裹query的值,而query内部dateTime的参数值又使用了未转义的双引号,导致JSON解析器误判query字符串提前结束,后续的2024...成为无效的JSON结构。
  • OpenTripPlanner的GraphQL API接受dateTime为ISO 8601格式的字符串,无需特殊对象,格式正确即可。

解决方法

推荐两种避免手动转义的安全写法:

方法1:用json.dumps自动处理转义

import requests
import json

headers = {
    'Content-Type': 'application/json',
    'OTPTimeout': '180000',
}

# 三引号编写原始GraphQL查询,无需手动转义
graphql_query = '''
query {
  trip(
    from: {coordinates: {latitude: 27.94942, longitude: -82.47202}},
    to: {coordinates: {latitude: 27.99107, longitude: -82.45619}},
    dateTime: "2024-11-18T14:00:00.000Z"
  ) {
    tripPatterns {
      duration
      distance
      legs {
        distance
        duration
        id
        mode
      }
    }
  }
}
'''

# 自动处理JSON格式与引号转义
data = json.dumps({"query": graphql_query})

response = requests.post('http://localhost:8080/otp/transmodel/v3', headers=headers, data=data)
json_string = response.text

方法2:用requests的json参数自动序列化

import requests

headers = {
    'OTPTimeout': '180000',
}

graphql_query = '''
query {
  trip(
    from: {coordinates: {latitude: 27.94942, longitude: -82.47202}},
    to: {coordinates: {latitude: 27.99107, longitude: -82.45619}},
    dateTime: "2024-11-18T14:00:00.000Z"
  ) {
    tripPatterns {
      duration
      distance
      legs {
        distance
        duration
        id
        mode
      }
    }
  }
}
'''

# 直接传递字典,requests自动转为正确JSON
response = requests.post(
    'http://localhost:8080/otp/transmodel/v3',
    headers=headers,
    json={"query": graphql_query}
)
json_string = response.text

关键说明

  • 无需手动转义引号,依赖Python的JSON处理库自动处理,避免人为错误。
  • dateTime仅需传递ISO 8601格式的字符串即可被API正确解析。

内容的提问来源于stack exchange,提问作者James Polo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 03:22:44