2016-08-04 2 views
0

У меня есть схема JSON для новых заказов, которая состоит из списка заказов и адреса.Как проверить требуемые элементы массива JSON SCHEMA

{ 
    "$schema": "http://json-schema.org/draft-04/schema#", 
    "type": "array", 
    "properties": { 
    "order": { 
     "type": "array", 
     "items": { 
     "type": "array", 
     "properties": { 
      "product_id": { 
      "type": "integer" 
      }, 
      "quantity": { 
      "type": "integer" 
      } 
     }, 
     "required": [ 
      "product_id", 
      "quantity" 
     ] 
     } 
    }, 
    "address": { 
     "type": "array", 
     "properties": { 
     "name": { 
      "type": "string" 
     }, 
     "phone": { 
      "type": "integer" 
     }, 
     "address1": { 
      "type": "string" 
     }, 
     "address2": { 
      "type": "string" 
     }, 
     "city": { 
      "type": "string" 
     }, 
     "state_or_region": { 
      "type": "string" 
     }, 
     "country": { 
      "type": "string" 
     } 
     }, 
     "required": [ 
     "name", 
     "phone", 
     "address1", 
     "city", 
     "state_or_region", 
     "country" 
     ] 
    } 
    }, 
    "required": [ 
    "order", 
    "address" 
    ] 
} 

Но это не похоже на самом деле проверить элементы на всех (я использую Laravel 5.2 с "justinrainbow/json-schema": "~2.0"):

$refResolver = new \JsonSchema\RefResolver(new \JsonSchema\Uri\UriRetriever(), new \JsonSchema\Uri\UriResolver()); 
$schema = $refResolver->resolve(storage_path('schemas\orders.post.json')); 

$errors = []; 
$input = Request::input(); 

// Validate 
$validator = new \JsonSchema\Validator(); 
$validator->check($input, $schema); 

$msg = []; 
if ($validator->isValid()) { 
    return Response::json(['valid'], 200, [], $this->pritify); 
} else { 
    $msg['success'] = false; 
    $msg['message'] = "JSON does not validate"; 
    foreach ($validator->getErrors() as $error) { 
     $msg['errors'][] = [ 
      'error' => ($error['property'] = ' ') ? 'wrong_data' : $error['property'], 
      'message' => $error['message'] 
     ]; 
    } 
    return Response::json($msg, 422, [], $this->pritify); 
} 

Запрос, как это всегда приходит в силе:

{ 
    "order": [ 
     { 
      "product_id": 100, 
      "quantity": 1 
     }, 
     { 
      "product_id": 0, 
      "quantity": 2 
     } 
    ], 
    "address": [] 
} 

Любые идеи, что я делаю неправильно?

+0

http://jsonlint.com. Моя IDE бросила ошибки в конце запятых после скобок после '' country '' – aynber

+0

Извините, удалил. Существует еще несколько подтверждений, это сокращенный пример – Peon

ответ

1

У вас есть беспорядочный массив и типы объектов. Единственное значение массива в вашей схеме должно быть порядка. Фиксированная схема:

{ 
    "$schema": "http://json-schema.org/draft-04/schema#", 
    "type": "object", 
    "properties": { 
    "order": { 
     "type": "array", 
     "items": { 
     "type": "object", 
     "properties": { 
      "product_id": { 
      "type": "integer" 
      }, 
      "quantity": { 
      "type": "integer" 
      } 
     }, 
     "required": [ 
      "product_id", 
      "quantity" 
     ] 
     } 
    }, 
    "address": { 
     "type": "object", 
     "properties": { 
     "name": { 
      "type": "string" 
     }, 
     "phone": { 
      "type": "integer" 
     }, 
     "address1": { 
      "type": "string" 
     }, 
     "address2": { 
      "type": "string" 
     }, 
     "city": { 
      "type": "string" 
     }, 
     "state_or_region": { 
      "type": "string" 
     }, 
     "country": { 
      "type": "string" 
     } 
     }, 
     "required": [ 
     "name", 
     "phone", 
     "address1", 
     "city", 
     "state_or_region", 
     "country" 
     ] 
    } 
    }, 
    "required": [ 
    "order", 
    "address" 
    ] 
} 

И проверки ошибок, которые я получил с вами проверить данные:

JSON does not validate. Violations: 
[address.name] The property name is required 
[address.phone] The property phone is required 
[address.address1] The property address1 is required 
[address.city] The property city is required 
[address.state_or_region] The property state_or_region is required 
[address.country] The property country is required 
+0

hmm, но в этом случае я получаю значение «Array», но требуется объект «', поскольку '$ input = Request :: input();' создает массив подобная структура – Peon

+0

В вашем примере данных «адрес»: [], но это будет объект как «адрес»: {«name»: «Kostya»}, поэтому ваша ошибка проверки также верна. Я считаю, что вся путаница заключается в том, что пустой пул PHP может быть представлен как пустой пул JSON или пустой объект JSON, но ассоциативный массив PHP может быть представлен как объект JSON. –

+0

Спасибо. Я думаю, что именно так Laravel обрабатывает запросы. Я решил проблему, добавив '$ input = json_decode (json_encode ($ input));' после запроса. – Peon

Смежные вопросы