iteks/laravel-json

Laravel JSON 包是一款用于简化 JSON 数据操作的 Laravel 扩展包,提供了将 JSON 数据无缝转换为集合或数组,并带有属性过滤功能。

v1.2.0 2024-07-30 02:08 UTC

This package is auto-updated.

Last update: 2024-08-30 03:04:52 UTC


README

Laravel JSON

Total Downloads Latest Stable Version License

Laravel JSON 包是一款功能强大且灵活的工具,旨在增强 Laravel 应用程序中 JSON 数据的处理。凭借其直观的 API,开发人员可以轻松地将 JSON 文件转换为 Laravel 集合或关联数组,从而简化数据操作和访问。无论是处理配置文件、数据集导入还是任何 JSON 格式的数据源,此包都能简化处理过程,让您专注于构建功能丰富的应用程序。考虑到灵活性,它支持可选的属性过滤,使您能够根据需求精确检索数据。此外,通过列定义强制执行任何 JSON 模型列的数据结构,确保每次交互时 JSON 数据的一致性。《Laravel JSON》适用于所有规模的项目,旨在简化开发工作流程,使 JSON 数据处理变得轻松。

iteks 提供,由 jeramyhing 开发。

开始使用

需要 PHP 8.1+

通过 Composer 包管理器安装 Laravel JSON

composer require iteks/laravel-json

用法

包含 Json 门面。

use Iteks\Support\Facades\Json;

示例 Json 数据集

此 JSON 数据集用于 Json::toCollection()Json::toArray() 方法示例。

[
    {
        "border": "3px solid white",
        "coordinates": [
          51.70696,
          40.34103
        ],
        "password": "xXeagle-*******"
    },
    {
        "border": "1px dotted amber",
        "coordinates": [
          11.80583,
          108.05094
        ],
        "password": "xXmeerkat-******"
    },
    {
        "border": "4px dotted gray",
        "coordinates": [
          116.82882,
          74.57905
        ],
        "password": "xXcat-*******"
    }
]

top

JSON 辅助函数

Json::toCollection()

toCollection 方法将 JSON 文件转换为 Laravel 集合的集合。这在您需要使用 Laravel 集合方法的便利性和功能来操作 JSON 数据时特别有用。

无参数使用

当您使用 toCollection 而不指定属性时,它将简单地将整个 JSON 文件转换为集合,其中每个元素都是一个表示 JSON 对象的集合。

$collection = Json::toCollection(database_path('data/test.json'));
Illuminate\Support\Collection {#298 ▼
  #items: array:3 [▼
    0 => 
Illuminate\Support\Collection {#299 ▼
      #items: array:3 [▼
        "border" => "3px solid white"
        "coordinates" => array:2 [▼
          0 => 51.70696
          1 => 40.34103
        ]
        "password" => "xXeagle-*******"
      ]
      #escapeWhenCastingToString: false
    }
    1 => 
Illuminate\Support\Collection {#300 ▼
      #items: array:3 [▼
        "border" => "1px dotted amber"
        "coordinates" => array:2 [▼
          0 => 11.80583
          1 => 108.05094
        ]
        "password" => "xXmeerkat-******"
      ]
      #escapeWhenCastingToString: false
    }
    2 => 
Illuminate\Support\Collection {#301 ▼
      #items: array:3 [▼
        "border" => "4px dotted gray"
        "coordinates" => array:2 [▼
          0 => 116.82882
          1 => 74.57905
        ]
        "password" => "xXcat-*******"
      ]
      #escapeWhenCastingToString: false
    }
  ]
  #escapeWhenCastingToString: false
}
// Iterate over the collection
foreach ($collection as $item) {
    // Access properties like in any Laravel collection
    echo $item->get('border');
}

有参数使用

当您提供属性名称作为第二个参数时,toCollection 将创建一个集合,其中每个项目都是 JSON 对象中指定属性的值。

$collection = Json::toCollection(database_path('data/test.json'), 'border');
Illuminate\Support\Collection {#297 ▼
  #items: array:3 [▼
    0 => "3px solid white"
    1 => "1px dotted amber"
    2 => "4px dotted gray"
  ]
  #escapeWhenCastingToString: false
}

top

Json::toArray()

toArray 方法将 JSON 文件转换为 PHP 数组。此方法在您需要简单数组表示的 JSON 数据进行进一步处理或不需要 Laravel 的集合方法时特别理想。

无参数使用

未指定属性时,toArray 将整个 JSON 文件转换为嵌套数组,其中每个元素都是一个表示 JSON 对象的关联数组。

$array = Json::toArray(database_path('data/test.json'));
array:3 [▼
  0 => array:3 [▼
    "border" => "3px solid white"
    "coordinates" => array:2 [▼
      0 => 51.70696
      1 => 40.34103
    ]
    "password" => "xXeagle-*******"
  ]
  1 => array:3 [▼
    "border" => "1px dotted amber"
    "coordinates" => array:2 [▼
      0 => 11.80583
      1 => 108.05094
    ]
    "password" => "xXmeerkat-******"
  ]
  2 => array:3 [▼
    "border" => "4px dotted gray"
    "coordinates" => array:2 [▼
      0 => 116.82882
      1 => 74.57905
    ]
    "password" => "xXcat-*******"
  ]
]
// Access the array directly
foreach ($array as $item) {
    echo $item['border'];
}

有参数使用

提供属性名称作为第二个参数,toArray 将生成一个仅包含每个 JSON 对象中指定属性值的数组。

$array = Json::toArray(database_path('data/test.json'), 'border');
array:3 [▼
  0 => "3px solid white"
  1 => "1px dotted amber"
  2 => "4px dotted gray"
]

top

JSON 特性(DefinesJsonColumns)

DefinesJsonColumns 特性和辅助的 enforceDefinition 方法允许您为 JSON 数据库列定义和强制 JSON 数据结构。这确保了与 JSON 数据列的任何交互都将始终包含符合其 JSON 定义的数据结构。

简单地将DefinesJsonColumns特性应用于包含JSON列的模型。在模型上使用$jsonDefinitions属性定义JSON结构,然后开始使用enforceDefinition来对JSON输入执行列定义。

导入模型特性和配置JSON定义。

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Iteks\Support\Traits\DefinesJsonColumns;

class ExampleModel extends Model
{
  use DefinesJsonColumns;

  protected $jsonDefinitions = [
    'profile' => [
      'name' => 'string',
      'age' => 'integer',
      'avatar' => 'string',
    ],
    'address' => [
      'street' => 'string',
      'city' => 'string',
      'state' => 'string',
      'zip' => 'integer',
      'geo_coordinates' => 'array',
    ],
  ];
}

您可以配置多个JSON列的定义。

Json::enforceDefinition()

您可以在应用程序逻辑的任何地方使用enforceDefinition方法,针对您打算插入模型JSON列的目标JSON输入。

$addressJson = json_encode($addressData);
$enforcedJson = Json::enforceDefinition(ExampleModel::class, 'address', $addressJson);

$exampleModel->address = $enforcedJson;
$exampleModel->save();

如果输入JSON为null或缺少任何定义的键,定义仍然会通过添加带有null值的缺失键来执行。如果输入JSON包含不在JSON列定义中的额外键值对,则它们将被排除。

在表单请求的prepareForValidation方法中的使用

在包含JSON输入的目标请求属性上应用enforceDefinition方法。传递模型类、列和请求属性JSON值。

namespace App\Http\Requests;

use App\Models\ExampleModel;
use Illuminate\Foundation\Http\FormRequest;
use Iteks\Support\Facades\Json;

class ExampleFormRequest extends FormRequest
{
    protected function prepareForValidation(): self
    {
        $this->merge([
            'request_attribute' => Json::enforceDefinition(ExampleModel::class, 'profile', $this->request_attribute),
        ]);

        return $this;
    }
}

top