【问题标题】:How can I JSON.parse request body correctly in postman如何在邮递员中正确地 JSON.parse 请求正文
【发布时间】:2021-12-28 08:14:55
【问题描述】:

我的目标是从 responseBody 设置环境变量,以便稍后在其他请求中重用它。在我这样做之前,我想先获取该变量,但是我遇到了问题。

所以我的 responseBody 看起来像:

{
"email":"test_email",
"tokens":"{'refresh': 'sample_refresh', 'access': 'sample access'}"
}

请注意,令牌是作为字符串传递的。 这是邮递员测试部分的代码:

response = JSON.parse(responseBody);
tokens = response.tokens
accesstry1 = tokens["access"]
accesstry2 = tokens[1]

console.log(tokens)
Result: "{'refresh': 'sample_refresh', 'access': 'sample access'}"
console.log(accesstry1)
Result: undefined
console.log(accesstry2)
Result: "'"

我也尝试解析 tokens 变量,但它给了我一个错误:

tokens = response.tokens 
tokens_parsed = JSON.parse(tokens)
Result JSONError: Unexpected token '\'' at 1:2 {'refresh': 
       'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVza

【问题讨论】:

    标签: json postman postman-testcase


    【解决方案1】:

    在 JSON 中只使用双引号, 如有疑问,请检查 JSON 的有效性 使用https://jsonlint.com/ 或类似的工具。

    这对我有用:

    var respText = "{\r\n\t\"email\": \"test_email\",\r\n\t\"tokens\": {\r\n\t\t\"refresh\": \"sample_refresh\",\r\n\t\t\"access\": \"sample access\"\r\n\t}\r\n}";
    var respJson = JSON.parse(respText);
    console.log(respJson.tokens.access);
    

    PS:我使用 https://www.freeformatter.com/json-escape.html 将 json 转换为单行转义字符串

    【讨论】:

    • Mhh 实际上很有趣的链接,从现在开始我会尝试使用它们......奇怪的是,我检查并从后端传递双引号中的键,我会进一步看看为什么它会这样切换。但是,test_email、sample_refresh 和 sample_access 这些是动态变量。对于每个请求,它们都会有所不同,并且硬编码这行不通吗?
    • respText 是一个变量,因此任何有效和转义的 JSON(就像由 JSON.stringify() 方法产生的一样,应该可以工作,没有硬编码)
    • 我的意思是 respText = "{\r\n\t\"email\": \"test_email\" 这不能像您在示例中那样硬编码,因为不同的用户有不同的电子邮件...respText = "{\r\n\t\"email\": \"test1@email.com\" respText = "{\r\n\t\"email\": \"test2@email.com\" 等等...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    • 2021-11-25
    • 2018-11-13
    • 1970-01-01
    • 2018-08-20
    • 1970-01-01
    相关资源
    最近更新 更多