php - PHP:我可以在它的第一个深度分割一个 JSONstring 而不必重新编码?
问题描述
由于我不知道 behat 是否可以将 Behat FeatureContext 函数参数注入字符串以外的任何内容,因此我想知道是否可以拆分字符串,从而留下一个 json_objects 数组。
我已经设法用json_decode
and做到了这一点json_encode
,但是当我第一次解码对象字符串时感觉有点重复,只是将它编码回单个对象。
每个示例具有以下 Behat 功能:
Feature: Provide a consistent standard JSON API endpoint
In order to build interchangeable front ends
As a JSON API developer
I need to allow Create, Read, Update, and Delete functionality
Background:
Given there are Albums with the following details:
"""
[{
"artist":"Pink Floyd",
"title":"The Dark Side of the Moon",
"songs":[
{"title":"Speak to Me", "length":254}
{"title":"Breathe", "length":192}
{"title":"On the Run", "length":188}
]
},
{
"artist":"AC/DC",
"title":"Back to Black",
"songs":[
{"title":"Hells Bells", "length":205}
{"title":"Shoot to Thrill", "length":302}
{"title":"What Do You Do for Money Honey", "length":244}
]
}]
"""
And the "Content-Type" request header is "application/json"
以及 FeatureContext.php 中的以下函数:
...
public function thereAreAlbumsWithTheFollowingDetails(string $jsonString) {
$albums = json_decode($jsonString, true);
foreach ($albums as $album) {
$albumJson = json_encode($album);
$this->apiContext->setRequestBody($albumJson);
$this->apiContext->requestPath("/api/album", "POST");
}
}
...
解决方案
据我了解,您想添加一些数据来设置场景,在这种情况下,我会远离 json,因为这是一个实现细节:
Given there are Albums with the following details:
| artist | title | songs |
| Pink Floyd | The Dark Side of the Moon | Speak to Me, Breathe, On the Run |
| AC/DC | Back to Black | Hells Bells, Shoot to Thrill, What Do You Do for Money Honey |
...
如果需要,然后在FeatureContext上将数据转换为 json,但就个人而言,如果你做得正确,我只会注入应该在/api/album控制器中使用的相同服务来创建专辑。
推荐阅读
- postgresql - 出现错误:ValueError:不支持的格式字符:'('
- macos - DevTools 在 Intellij 中重新启动两次
- ios - 无法将我的 iOS 应用程序与 Crashlytics 同步
- pulseaudio - 如何在 pulseaudio 上远程管理音量
- javascript - Node.js - 如何获取远程音频文件的持续时间?
- android - 如何使用 kotlin 在 android 上处理后退按钮 DrawerNavigation
- python - ruamel.yaml 安装另一个 python 包的问题
- kotlin - 如何为相同的资源使用多个路由
- javascript - 如何根据列表中的项目数多次显示通知
- python - 格式化文档名称