首页 > 解决方案 > PHP:我可以在它的第一个深度分割一个 JSONstring 而不必重新编码?

问题描述

由于我不知道 behat 是否可以将 Behat FeatureContext 函数参数注入字符串以外的任何内容,因此我想知道是否可以拆分字符串,从而留下一个 json_objects 数组。

我已经设法用json_decodeand做到了这一点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");
    }
}

...

标签: phpjsonbehatgherkin

解决方案


据我了解,您想添加一些数据来设置场景,在这种情况下,我会远离 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控制器中使用的相同服务来创建专辑。


推荐阅读