我需要編輯的檔案夾中有大約 3000 個 json 檔案。我做了一些研究,但我發現的一切似乎都不適用于我的情況。我相信這是因為將資料提取到陣列時,屬性中的資料位于子陣列中。
我需要打開每個檔案并編輯"trait_type"名稱。我需要為每種特征型別洗掉 Vehicle/ 。
例如我需要編輯
"trait_type": "Vehicle/Exterior"
并更改為此。
"trait_type": "Exterior"
任何幫助將非常感激。
JSON檔案
{
"name":"2020 Mercedes-Benz Sl550 ",
"description":"Fully Loaded",
"image":"http://www.websitename.com/images/2020_mercedes-benz_1.jpg",
"price":"69900",
"miles":4500,
"date":1647530418343,
"attributes":[
{
"trait_type":"Vehicle/Exterior",
"value":"Black"
},
{
"trait_type":"Vehicle/Interior",
"value":"Black"
},
{
"trait_type":"Vehicle/Engine",
"value":"4.7L V8 32V"
},
{
"trait_type":"Vehicle/Fuel",
"value":"GAS"
}
],
"Stock Number":"43212"
}
uj5u.com熱心網友回復:
- 用于
glob獲取所有 JSON 檔案名 - 對于每個檔案,讀取內容并將其轉換為
stdClass - 回圈,對任何出現的情況
attributes做一個簡單的str_replacetrait_type - 將
stdClass后面轉換為 JSON 字串 - 用新替換的內容覆寫每個檔案
$files = glob('*.json');
foreach ($files as $file) {
$json = json_decode(file_get_contents($file));
foreach($json->attributes as $attrib) {
if (isset($attrib->trait_type)) {
$attrib->trait_type = str_replace('Vehicle/', '', $attrib->trait_type);
}
}
file_put_contents($file, json_encode($json, JSON_PRETTY_PRINT));
}
您應該跳過JSON_PRETTY_PRINT,僅將其用于演示目的,因此更容易看到它Vehicle/實際上已被洗掉。顯然 PHP 應該對該目錄具有寫訪問權限。
uj5u.com熱心網友回復:
哦,沒有及時趕上:D
<?php
if(!is_dir('fixed')){
mkdir('fixed');
}
foreach(glob('*.json') as $json_file){
$data = json_decode(file_get_contents($json_file));
foreach($data->attributes as $key => $attribute){
$data->attributes[$key]->trait_type = preg_replace('/^vehicle\//i', '', $attribute->trait_type);
}
file_put_contents('fixed/'.$json_file, json_encode($data, JSON_PRETTY_PRINT));
}
uj5u.com熱心網友回復:
您可以使用array_walk_recursive,它將更新陣列,您可以再次將其編碼為 JSON :
<?php
$data = '{"name":"2020 Mercedes-Benz Sl550 ","description":"Fully Loaded","image":"http:\/\/www.websitename.com\/images\/2020_mercedes-benz_1.jpg","price":"69900","miles":4500,"date":1647530418343,"attributes":[{"trait_type":"Vehicle\/Exterior","value":"Black"},{"trait_type":"Vehicle\/Interior","value":"Black"},{"trait_type":"Vehicle\/Engine","value":"4.7L V8 32V"},{"trait_type":"Vehicle\/Fuel","value":"GAS"}],"Stock Number":"43212"}';
// better use a named function if you call it very often
function my_modifier (&$v, $k){
if ($k == "trait_type")
$v = 'XYZ';
}
$arr = json_decode($data, true);
array_walk_recursive($arr, 'my_modifier');
$data = json_encode($arr);
// done, $data is upadted.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/452093.html
