【问题标题】:How to send JSON object as JSON String with Postman?如何使用 Postman 将 JSON 对象作为 JSON 字符串发送?
【发布时间】:2018-06-27 06:44:43
【问题描述】:

我想发送一个 JSON 请求,但问题是我需要将我的 userPropertiesAsJsonString 字段作为 JSON 字符串发送。

如何将 userPropertiesAsJsonString 作为 JSON 字符串发送?

{
    "User" : {
        "userId" : "11111",
        "userPropertiesAsJsonString" : ?
    }
}

userPropertiesAsJsonString 是;

{
    "properties" : {
        "propertyName" : "test",
        "propertyDesc" : "desc"
    }
}

【问题讨论】:

  • 在 Postman 中粘贴您在此处发布的内容有什么问题?如果我没记错的话应该可以工作。只需确保引号用\" 转义,而不仅仅是"
  • 如果这是在 JavaScript 中,你不能在那里做JSON.stringify(userPropertiesAsJsonString) 吗?

标签: javascript json postman


【解决方案1】:

试试这个:

{
    "User" : {
        "userId" : "11111",
        "userPropertiesAsJsonString" : "{\"properties\" : {\"propertyName\" : \"test\",\"propertyDesc\" : \"desc\"}}"
    }
}

【讨论】:

  • 这必须在一行中,这是一个相当糟糕的解决方案。我希望我们可以使用'' 或(反引号)
【解决方案2】:

Jason Mullings' 的回答对我不起作用,但它是一个很好的基础,让我能够为与您的问题非常相似的问题提出解决方案。

在预请求脚本选项卡中,

const userPropertiesAsJsonString = {
    "properties" : {
        "propertyName" : "test",
        "propertyDesc" : "desc"
    }
}

pm.environment.set(
    'userPropertiesAsJsonString',
    JSON.stringify(JSON.stringify(userPropertiesAsJsonString))
);

然后,在“正文”选项卡中,

{
    "User" : {
        "userId" : "11111",
        "userPropertiesAsJsonString" : {{userPropertiesAsJsonString}}
    }
}

userPropertiesAsJsonString 变量进行两次字符串化将允许您转义 JSON 字符串(从this answer 获得的解决方案;有关更详细的说明,请参阅this gist),然后您将获得一个看起来像这样的请求正文sanatsathyan提供的答案中的那个。

【讨论】:

  • 使用 JSON.stringify 两次很棒,它是 Postman 中唯一对我有用的解决方案,谢谢。
  • @sabriele 很高兴能得到一些帮助 ;-)
【解决方案3】:

预请求脚本:

let query = {}

pm.environment.set('query', JSON.stringify(query));

正文:

{{query}}

【讨论】:

  • 嵌套的 JSON 需要转义,所以不起作用
【解决方案4】:

由于 JSON 表示 JavaScript Object Notation,因此您只需将 userPropertiesAsJsonString 复制到原始 JSON 中即可:

{
    "User" : {
        "userId" : "11111",
        "userPropertiesAsJsonString" : {
            "properties" : {
                "propertyName" : "test",
                "propertyDesc" : "desc"
            }
        }
    }
}

将此 JSON 复制并粘贴到 Postman 请求正文(原始格式)并设置标头“Content-Type: application/json”。

如果你必须在请求之前做更多花哨的事情,你可以在 Postman 中执行一个预请求脚本:https://www.getpostman.com/docs/postman/scripts/pre_request_scripts

有关 JSON 的更多信息,请参见此处:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON

【讨论】:

  • 这就是我想要的,只使用原始 JSON 而不是字符串 - 因为它使用 Postman 来 POST 请求有效负载,JSON.stringify() 将无法工作,因为应用程序将失败验证,因为它检查架构是有效的 JSON。
猜你喜欢
  • 1970-01-01
  • 2020-09-15
  • 1970-01-01
  • 2018-11-05
  • 2013-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-06
相关资源
最近更新 更多