теперь измени скрипт на такое отображение csv в json name,iso_code,dafif_code
“s”,”ss”,”sss”
что должно получится в json файле:
{
“source”:“”,“schema”: “”,
“data”: [
{
“$source”: “”,
“title”: “Country”,
“items”: [
{
“name”: ”s”,
“iso_code”: “ss”,
“dafif_code”: “sss”,
}
]
}
]
}
/N, N/A, "-" оставляй пустыми, пустые "" тоже не удаляй
Assistant
Понял, теперь нужно изменить скрипт так, чтобы он:
Парсил CSV с полями name, iso_code, dafif_code.
Формировал JSON с ключами $source, $schema, data.
В data — список с одним элементом { "$source": "", "title": "Country", "items": [...] }.
В — список объектов из CSV.
User
нет, немного не так
Корневая структура с source,schema и ключом data.
В data — список с одним элементом, где есть $source, title: "Country" и items — список объектов.
Каждый объект — это строка из CSV, при этом пустые поля остаются, а значения \N, -, N/A конвертируются в пустую строку "".
Поля сохраняем как строки.
Assistant
Понял вас, доработаю скрипт по вашим точным требованиям:
Корневая структура: $source, $schema, data
data — список с одним элементом { "$source": "", "title": "Country", "items": [...] }
В items — список строк из CSV
User
теперь скрипт должен преобразовывать так: airlines,airline_id,source_airport,source_airport_id,destination_airport,destination_airport_id,codeshare,stops,equipment
2B,410,AER,2965,KZN,2990,,0,CR2
что должно получится в json файле:
{
“source”:“”,“schema”: “”,
“data”: [
{
“source”: “”,
“title”: “Route”,
“items”: [
{
“airline”: ”2B”,
“airline_id”: {
“ref”: “json_examples/json_instances/airlines.json”,
“title”: “Airline”,
“0”: {
“id”: 410
}
},
“source_airport”: “AER”,
“source_airport_id”: {
“ref”: “json_examples/json_instances/airports.json”,
“title”: “Airport”,
“0”: {
“id”: 2990
}
},
“codeshare”: “”,
“stops”: 0,
“equipment”: {
“$ref”: “json_examples/json_instances/planes.json”,
“title”: “Plane”,
“0”: {
“name”: “CR2”
}
}
}
]
}
]
}
значения \N, N/A, "", "-" всё так же должны преобразовываться в ""
Assistant
User
ещё надо учесть, что поля id и stops должны быть integer,
Assistant
User
если id нет, то пусть лучше будет ошибка, id должен быть всегда в файле csv
Assistant
User
уточню, что поля id ВЛОЖЕННЫЕ, как в этом элементе, например: “destination_airport_id”: {
“$ref”: “json_examples/json_instances/airports.json”,
“title”: “Airport”,
“0”: {
“id”: 2990
}
}, должны быть integer, то есть 2990 это именно число integer
Assistant
User
если вдруг id нет, то не выводи ошибку, а удаляй эти строчки
Assistant
User
а и выводи строки, которые были удалены
Assistant
User
нужно, чтобы ты написал подобную схему: пример для типа car {
"source": "",
"type": "object",
"title": "Car",
"namespace": "Mephi.Cybernetics.Race.Core.Tests",
"properties": {
"vin": {
"type": "string",
"description": "A vehicle identification number"
},
"model": {
"type": "object",
"ref": "C:\Users\kftin\Documents\home\unv\2024_2025\курсовая_6\race\src\Mephi.Cybernetics.Race.Core.Tests\ObjectMapping\schemas\model.json",
"description": "A vehicle's model"
}
},
"meta": {
"keys": {
"vin": "vin"
}
}
} пример для типа factory {
"schema": "",
"type": "object",
"namespace": "Mephi.Cybernetics.Race.Core.Tests",
"title": "Factory",
"properties": {
"id": {
"type": "integer",
"description": "artificial identifier of factory"
},
"inn": {
"type": "ulong",
"description": "a sequence of numbers that contains basic information about the legal owner"
},
"ogrnip": {
"type": "string",
"description": "a sequence of numbers that contains basic information about the company"
},
"address": {
"type": "string",
"description": "factory's legal address"
},
"models": { //многие ко многим
"type": "array",
"$ref": "C:\Users\kftin\Documents\home\unv\2024_2025\курсовая_6\race\src\Mephi.Cybernetics.Race.Core.Tests\ObjectMapping\schemas\model.json",
"description": "what models produce this factory"
}
},
"meta": {
"keys": {
"id": "id",
"ogrnip_inn": [ "ogrnip", "inn" ]
}
}
}
Assistant
Конечно! Ниже — пример JSON-схемы для вашего типа Airline (по аналогии с вашими примерами car и factory), с описаниями и типами для атрибутов из вашего объекта.
{
"$source": "",
"type": "object",
"title": "Airline",
"namespace": "Your.Namespace.Here", // замените на ваш namespace
"properties": {
"id": {
"type": "integer",
"description": "Unique identifier of the airline"
},
"name": {
"type": "string",
"description": "Official name of the airline"
},
"alias": {
"type": "string",
"description": "Alternative or short name"
},
"IATA": {
"type": "string",
"description": "IATA airline code"
},
"ICAO": {
"type": "string",
"description": "ICAO airline code"
},
"callsign": {
"type": "string",
"description": "Radio callsign of the airline"
},
"country": {
"type": "object",
"$ref": "json_examples/json_instances/countries.json",
"title": "Country",
"description": "Country of the airline"
},
"active": {
"type": "string",
"description": "Indicates if airline is active (Y/N)"
}
},
"meta": {
"keys": {
"id": "id"
}
}
}
User
namespace оставь такой же, как был, теперь сделай для airport: "id": 14110,
"name": "Melitopol Air Base",
"city": "Melitopol",
"country": {
"$ref": "json_examples/json_instances/countries.json",
"title": "Country",
"0": {
"name": "Ukraine"
}
},
"IATA": "",
"ICAO": "UKDM",
"latitude": 46.880001,
"longitude": 35.305,
"altitude": 0,
"timezone": "",
"DST": "",
"tz_database_timezone": "",
"type": "airport",
"source": "OurAirports"
Assistant
Вот JSON-схема для типа Airport с учетом ваших данных и сохранением namespace из примера:
{
"$source": "",
"type": "object",
"title": "Airport",
"namespace": "Mephi.Cybernetics.Race.Core.Tests",
"properties": {
"id": {
"type": "integer",
"description": "Unique identifier of the airport"
},
"name": {
"type": "string",
"description": "Name of the airport"
},
"city": {
"type": "string",
"description": "City where the airport is located"
},
"country": {
"type": "object",
"$ref": "json_examples/json_instances/countries.json",
"title": "Country",
"description": "Country of the airport"
},
"IATA": {
"type": "string",
"description": "IATA airport code"
},
"ICAO": {
"type": "string",
"description": "ICAO airport code"
},
"latitude": {
"type": "number",
"description": "Latitude coordinate of the airport"
},
"longitude": {
"type": "number",
"description": "Longitude coordinate of the airport"
},
"altitude": {
"type": "number",
"description": "Altitude of the airport (in feet)"
},
"timezone": {
"type": "string",
"description": "Timezone abbreviation"
},
"DST": {
"type": "string",
"description": "Daylight saving time status"
},
"tz_database_timezone": {
"type": "string",
"description": "Timezone in tz database format"
},
"type": {
"type": "string",
"description": "Type of the airport"
},
"source": {
"type": "string",
"description": "Source of the airport data"
}
},
"meta": {
"keys": {
"id": "id"
}
}
}
User
number в типах надо заменить long
Assistant
Понял, заменяю типы "number" на "long" (обычно "long" — это 64-битный целочисленный тип, но, видимо, у вас используется именно такой тип для чисел с плавающей точкой, либо принята своя спецификация).
Вот исправленная схема с типом "long" в нужных местах:
вот пример: пример для типа factory {
"schema": "",
"type": "object",
"namespace": "Mephi.Cybernetics.Race.Core.Tests",
"title": "Factory",
"properties": {
"id": {
"type": "integer",
"description": "artificial identifier of factory"
},
"inn": {
"type": "ulong",
"description": "a sequence of numbers that contains basic information about the legal owner"
},
"ogrnip": {
"type": "string",
"description": "a sequence of numbers that contains basic information about the company"
},
"address": {
"type": "string",
"description": "factory's legal address"
},
"models": { //многие ко многим
"type": "array",
"ref": "json_examples/json_instances/airlines.json",
"title": "Airline",
"0": {
"id": 19016
}
},
"source_airport": "OSS",
"source_airport_id": {
"ref": "json_examples/json_instances/airports.json",
"title": "Airport",
"0": {
"id": 2912
}
},
"codeshare": "",
"stops": 0,
"equipment": {
"$ref": "json_examples/json_instances/planes.json",
"title": "Plane",
"0": {
"name": "734"
}
}
}
Assistant
User
для airline_id после description ничего добавлять не нужно и убери все required, и ключом для route будут airline_id, source_airport_id, destination_airport_id, eqipment
Assistant
User
такое же для countries
Assistant
Ниже пример JSON-схемы для типа Country, сделанной в том же стиле, что и ранее:
Если ваши объекты "countries" имеют другие поля — укажите, я подкорректирую.
Также, если нужно сделать какие-то поля ключами составного типа (массив) — скажите.
User
в $source ошибка там вместо json_instances в пути json_schemas
Assistant
Спасибо за замечание! Вот исправленная схема для Country с правильным путём в $source:
Понял задачу. Сделаю скрипт, который на вход принимает CSV (в формате вашего примера) и формирует JSON структуру согласно требованиям:
Корневая структура с $source, $schema и ключом data.
В data — список с одним элементом, где есть $source, title: "Airlines" и items — список объектов.
Каждый объект — это строка из CSV, при этом пустые поля остаются, а значения \N, -, N/A конвертируются в пустую строку "".
Поле country становится вложенным объектом по шаблону с $ref, title и индексом 0 с именем страны.
Значение поля id конвертируем в число (int).
Остальные поля сохраняем как строки.
Вот обновлённый скрипт с комментариями:
import csv
import json
import sys
def sanitize_value(val):
# Преобразуем специальные значения в пустую строку, убираем пробелы по краям
if val is None:
return ""
val = val.strip()
if val in {"\\N", "-", "N/A"}:
return ""
return val
def csv_to_custom_json(csv_file_path, json_file_path):
items = []
with open(csv_file_path, encoding='utf-8-sig') as csv_file:
reader = csv.DictReader(csv_file)
for row in reader:
# Обрабатываем каждое значение строки
cleaned_row = {k: sanitize_value(v) for k, v in row.items()}
# Преобразуем id в int, если возможно
try:
cleaned_row["id"] = int(cleaned_row["id"])
except (KeyError, ValueError):
cleaned_row["id"] = None # или можно пропустить/оставить как есть
# Построение вложенного объекта country
country_name = cleaned_row.get("country", "")
country_obj = {
"$ref": "json_examples/json_instances/countries.json",
"title": "Country",
"0": {
"name": country_name
}
}
# Заменяем поле country на вложенный объект
cleaned_row["country"] = country_obj
items.append(cleaned_row)
result = {
"$source": "",
"$schema": "",
"data": [
{
"$source": "",
"title": "Airlines",
"items": items
}
]
}
with open(json_file_path, 'w', encoding='utf-8') as json_file:
json.dump(result, json_file, ensure_ascii=False, indent=4)
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Использование: python script.py input.csv output.json")
sys.exit(1)
csv_input = sys.argv[1]
json_output = sys.argv[2]
csv_to_custom_json(csv_input, json_output)
print(f"Файл {csv_input} успешно преобразован в {json_output}")
Особенности
Код обрезает пробелы и меняет \N, -, N/A на пустую строку.
Учитывайте, что в вашем примере кавычки в CSV — обычные двойные, при корректном экспорте CSV Python должен корректно прочитать.
Можно доработать обработку ошибок, если нужно.
Если нужно, могу помочь дополнительно с запуском или валидацией!
Если будут ошибки — напишите, помогу разобраться!
Полный скрипт с этим изменением:
import csv
import json
import sys
def sanitize_value(val):
if val is None:
return ""
val = val.strip()
if val in {"\\N", "-", "N/A"}:
return ""
return val
def csv_to_custom_json(csv_file_path, json_file_path):
items = []
with open(csv_file_path, encoding='utf-8-sig') as csv_file:
reader = csv.DictReader(csv_file)
for row in reader:
cleaned_row = {k: sanitize_value(v) for k, v in row.items()}
try:
cleaned_row["id"] = int(cleaned_row["id"])
except (KeyError, ValueError):
cleaned_row["id"] = None
country_name = cleaned_row.get("country", "")
country_obj = {
"$ref": "json_examples/json_instances/countries.json",
"title": "Country",
"0": {
"name": country_name
}
}
cleaned_row["country"] = country_obj
items.append(cleaned_row)
result = {
"$source": "",
"$schema": "",
"data": [
{
"$source": "",
"title": "Airport", # Изменено "Airlines" -> "Airport"
"items": items
}
]
}
with open(json_file_path, 'w', encoding='utf-8') as json_file:
json.dump(result, json_file, ensure_ascii=False, indent=4)
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Использование: python script.py input.csv output.json")
sys.exit(1)
csv_input = sys.argv[1]
json_output = sys.argv[2]
csv_to_custom_json(csv_input, json_output)
print(f"Файл {csv_input} успешно преобразован в {json_output}")
Запускайте как и раньше. Если нужно ещё что-то изменить — дайте знать!
Понял, нужно добавить поля Latitude, Longitude, Altitude, Timezone и конвертировать их значения в числа (float или int), учитывая, что они могут быть отрицательными, если такие поля есть в CSV.
Вот изменённый скрипт, в котором добавлена логика преобразования этих полей в числа.
import csv
import json
import sys
def sanitize_value(val):
if val is None:
return ""
val = val.strip()
if val in {"\\N", "-", "N/A"}:
return ""
return val
def try_parse_number(val):
val = sanitize_value(val)
if val == "":
return None
try:
if '.' in val or 'e' in val.lower():
return float(val)
else:
return int(val)
except ValueError:
return None # если не число, возвращаем None или можно оставить пустой строкой
def csv_to_custom_json(csv_file_path, json_file_path):
# Список полей, которые надо парсить как числа
numeric_fields = {"Latitude", "Longitude", "Altitude", "Timezone"}
items = []
with open(csv_file_path, encoding='utf-8-sig') as csv_file:
reader = csv.DictReader(csv_file)
for row in reader:
cleaned_row = {}
for k, v in row.items():
if k in numeric_fields:
num_val = try_parse_number(v)
cleaned_row[k] = num_val if num_val is not None else ""
elif k == "id":
try:
cleaned_row[k] = int(sanitize_value(v))
except (ValueError, TypeError):
cleaned_row[k] = None
else:
cleaned_row[k] = sanitize_value(v)
# Построение вложенного объекта country
country_name = cleaned_row.get("country", "")
country_obj = {
"$ref": "json_examples/json_instances/countries.json",
"title": "Country",
"0": {
"name": country_name
}
}
cleaned_row["country"] = country_obj
items.append(cleaned_row)
result = {
"$source": "",
"$schema": "",
"data": [
{
"$source": "",
"title": "Airport", # или "Airlines", по вашему желанию
"items": items
}
]
}
with open(json_file_path, 'w', encoding='utf-8') as json_file:
json.dump(result, json_file, ensure_ascii=False, indent=4)
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Использование: python script.py input.csv output.json")
sys.exit(1)
csv_input = sys.argv[1]
json_output = sys.argv[2]
csv_to_custom_json(csv_input, json_output)
print(f"Файл {csv_input} успешно преобразован в {json_output}")
Кратко:
Для полей Latitude, Longitude, Altitude, Timezone, если значение можно преобразовать в число — оно становится числом (int или float).
Если значение пустое или в формате \N/-/N/A — заменяется пустой строкой "".
Все остальное остается без изменений.
Если в вашем CSV этих полей нет — просто добавьте их, скрипт обработает, если есть — тоже.
Если нужно — помогу с дополнительными доработками!
Спасибо за уточнение! Давайте я приведу полностью рабочий пример, где точно преобразуются именно эти поля в числа, а все остальные — обрабатываются как строки (с учётом замены \N, -, N/A на пустую строку), и поле id строго преобразуется в integer.
Вот проверенный код:
import csv
import json
import sys
def sanitize_value(val):
if val is None:
return ""
val = val.strip()
if val in {"\\N", "-", "N/A"} or val == "":
return ""
return val
def try_parse_number(val):
val = sanitize_value(val)
if val == "":
return ""
try:
# Если в числе есть точка или экспонента, преобразуем в float
if '.' in val or 'e' in val.lower():
return float(val)
else:
return int(val)
except ValueError:
# Если не получилось преобразовать — вернём исходную строку (либо пустую)
return ""
def csv_to_custom_json(csv_file_path, json_file_path):
numeric_fields = {"Latitude", "Longitude", "Altitude", "Timezone"}
items = []
with open(csv_file_path, encoding='utf-8-sig') as csv_file:
reader = csv.DictReader(csv_file)
for row in reader:
cleaned_row = {}
for k, v in row.items():
if k == "id":
# id обязательно в int, иначе пустая строка
val = sanitize_value(v)
try:
cleaned_row[k] = int(val)
except (ValueError, TypeError):
cleaned_row[k] = ""
elif k in numeric_fields:
cleaned_row[k] = try_parse_number(v)
else:
cleaned_row[k] = sanitize_value(v)
# Формируем вложенный объект country
country_name = cleaned_row.get("country", "")
country_obj = {
"$ref": "json_examples/json_instances/countries.json",
"title": "Country",
"0": {
"name": country_name
}
}
cleaned_row["country"] = country_obj
items.append(cleaned_row)
result = {
"$source": "",
"$schema": "",
"data": [
{
"$source": "",
"title": "Airport",
"items": items
}
]
}
with open(json_file_path, 'w', encoding='utf-8') as json_file:
json.dump(result, json_file, ensure_ascii=False, indent=4)
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Использование: python script.py input.csv output.json")
sys.exit(1)
csv_input = sys.argv[1]
json_output = sys.argv[2]
csv_to_custom_json(csv_input, json_output)
print(f"Файл {csv_input} успешно преобразован в {json_output}")
Поясню:
Для поля id — где возможно, превращаем в int, иначе ставим "".
Для перечисленных полей Latitude, Longitude, Altitude, Timezone пытаемся парсить числа (float или int).
Если данные не подходят — ставим пустую строку "".
Остальные поля — строки с заменой символов-плейсхолдеров на пустые строки.
Поле country формируем согласно вашему примеру.
Если хотите, я могу помочь проверить на вашем примере CSV. Пожалуйста, напишите, если понадобится.
items
Значения \N, N/A, - или пустые строки оставлял пустыми строками "", но не удалял ключи.
Нет вложенных объектов, как раньше — просто обычные поля.
Вот обновлённый скрипт:
import csv
import json
import sys
def sanitize_value(val):
if val is None:
return ""
val = val.strip()
if val in {"\\N", "N/A", "-", ""}:
return ""
return val
def csv_to_country_json(csv_file_path, json_file_path):
items = []
with open(csv_file_path, encoding='utf-8-sig') as csv_file:
reader = csv.DictReader(csv_file)
for row in reader:
cleaned_row = {k: sanitize_value(v) for k, v in row.items()}
items.append(cleaned_row)
result = {
"$source": "",
"$schema": "",
"data": [
{
"$source": "",
"title": "Country",
"items": items
}
]
}
with open(json_file_path, 'w', encoding='utf-8') as json_file:
json.dump(result, json_file, ensure_ascii=False, indent=4)
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Использование: python script.py input.csv output.json")
sys.exit(1)
csv_input = sys.argv[1]
json_output = sys.argv[2]
csv_to_country_json(csv_input, json_output)
print(f"Файл {csv_input} успешно преобразован в {json_output}")
Как использовать
python script.py countries.csv countries.json
где countries.csv примерно такой:
name,iso_code,dafif_code
s,ss,sss
Если данные в CSV содержат \N или N/A или - или пустую ячейку — в JSON поле будет пустая строка "", а все поля обязательно сохраняются.
Если нужно — помогу с дополнительными вопросами!
Значения \N, -, N/A меняются на ""
Пустые поля или пустые строки остаются (ни одно поле не удаляем)
Все поля строго строки (никаких чисел)
Вот скрипт с такими условиями:
import csv
import json
import sys
def sanitize_value(val):
if val is None:
return ""
val = val.strip()
if val in {"\\N", "-", "N/A"}:
return ""
return val
def csv_to_country_json(csv_file_path, json_file_path):
items = []
with open(csv_file_path, encoding='utf-8-sig') as csv_file:
reader = csv.DictReader(csv_file)
for row in reader:
cleaned_row = {}
for key in reader.fieldnames:
# Гарантируем сохранение всех полей без удаления
val = row.get(key, "")
cleaned_row[key] = sanitize_value(val)
items.append(cleaned_row)
result = {
"$source": "",
"$schema": "",
"data": [
{
"$source": "",
"title": "Country",
"items": items
}
]
}
with open(json_file_path, 'w', encoding='utf-8') as json_file:
json.dump(result, json_file, ensure_ascii=False, indent=4)
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Использование: python script.py input.csv output.json")
sys.exit(1)
csv_input = sys.argv[1]
json_output = sys.argv[2]
csv_to_country_json(csv_input, json_output)
print(f"Файл '{csv_input}' успешно преобразован в '{json_output}'")
Пояснения:
Использую reader.fieldnames при переборе, чтобы гарантированно сохранить все колонки даже если там пустые поля.
sanitize_value преобразует \N, -, или N/A к "".
Все значения строго строки (без преобразования в числа).
В итоговом JSON все поля сохранены.
Если нужно, могу помочь протестировать или внести дополнения!
Корневая структура с $source, $schema, и ключом data.
В data — список с одним объектом, где есть $source, title: "Route" и items — список объектов.
Каждый объект — строка из CSV с полями:
airline: строка
airline_id: вложенный объект с $ref и id (число)
source_airport: строка
source_airport_id: вложенный объект с $ref и id (число)
destination_airport: строка
destination_airport_id: вложенный объект с $ref и id (число)
codeshare: строка
stops: число
equipment: вложенный объект с $ref, title и name (строка)
Значения \N, N/A, "" и - преобразуются в пустую строку ""
Поля id и stops — числа.
Вот полноценный скрипт, выполняющий это преобразование:
import csv
import json
import sys
def sanitize_value(val):
if val is None:
return ""
val = val.strip()
if val in {"\\N", "N/A", "-", ""}:
return ""
return val
def try_parse_int(val):
val = sanitize_value(val)
if val == "":
return None
try:
return int(val)
except ValueError:
return None
def csv_to_route_json(csv_file_path, json_file_path):
items = []
with open(csv_file_path, encoding='utf-8-sig') as csv_file:
reader = csv.DictReader(csv_file)
for row in reader:
# Обработка и очистка значений
airline = sanitize_value(row.get("airlines"))
airline_id_val = try_parse_int(row.get("airline_id"))
source_airport = sanitize_value(row.get("source_airport"))
source_airport_id_val = try_parse_int(row.get("source_airport_id"))
destination_airport = sanitize_value(row.get("destination_airport"))
destination_airport_id_val = try_parse_int(row.get("destination_airport_id"))
codeshare = sanitize_value(row.get("codeshare"))
# Если codeshare равен пустой строке, оставляем пустым ("")
stops_val = try_parse_int(row.get("stops"))
equipment_name = sanitize_value(row.get("equipment"))
# Формируем вложенные структуры
airline_id = {
"$ref": "json_examples/json_instances/airlines.json",
"title": "Airline",
"0": {
"id": airline_id_val if airline_id_val is not None else ""
}
} if airline_id_val is not None else ""
source_airport_id = {
"$ref": "json_examples/json_instances/airports.json",
"title": "Airport",
"0": {
"id": source_airport_id_val if source_airport_id_val is not None else ""
}
} if source_airport_id_val is not None else ""
destination_airport_id = {
"$ref": "json_examples/json_instances/airports.json",
"title": "Airport",
"0": {
"id": destination_airport_id_val if destination_airport_id_val is not None else ""
}
} if destination_airport_id_val is not None else ""
equipment = {
"$ref": "json_examples/json_instances/planes.json",
"title": "Plane",
"0": {
"name": equipment_name
}
} if equipment_name != "" else ""
# Формируем объект элемента
item = {
"airline": airline,
"airline_id": airline_id,
"source_airport": source_airport,
"source_airport_id": source_airport_id,
"destination_airport": destination_airport,
"destination_airport_id": destination_airport_id,
"codeshare": codeshare,
"stops": stops_val if stops_val is not None else 0,
"equipment": equipment
}
items.append(item)
result = {
"$source": "",
"$schema": "",
"data": [
{
"$source": "",
"title": "Route",
"items": items
}
]
}
with open(json_file_path, "w", encoding="utf-8") as json_file:
json.dump(result, json_file, ensure_ascii=False, indent=4)
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Использование: python script.py input.csv output.json")
sys.exit(1)
csv_input = sys.argv[1]
json_output = sys.argv[2]
csv_to_route_json(csv_input, json_output)
print(f"Файл '{csv_input}' успешно преобразован в '{json_output}'")
Краткие пояснения:
Вложенные объекты (airline_id, source_airport_id, destination_airport_id, equipment) формируются даже если соответствующие значения пусты — в этом случае внутри вложенного объекта идёт пустая строка.
stops — число, если в CSV нет значения или оно некорректно — ставится 0.
Остальные значения обязательно строки с заменой специальных значений на пустые строки.
Если у вас могут быть пустые поля — они нормально подхватываются.
Если нужно, могу помочь с тестированием на ваших данных!
Да, поле stops и все поля *_id должны быть именно integer в сгенерированном JSON (а не строкой). При этом если в CSV пусто или недопустимое значение — для stops используем 0, для id — либо 0, либо можно пустое значение (но лучше согласованно).
Сейчас в моём скрипте:
Для stops: если нет значения или ошибка — ставится 0 (int).
Для id-полей: если нет значения или ошибка — внутри вложенного объекта "id" будет пустая строка "".
Если нужно, чтобы в случае отсутствия id было именно число, например 0, то поправим.
Исправленный код с гарантированной конвертацией id и stops в int (0 по умолчанию):
Все id-поля и stops — всегда integer, по умолчанию 0.
Пустые или неправильные значения в id и stops становятся 0.
Остальные поля — строки, с заменами \N, N/A, - на пустые строки.
Если нужно другое поведение — дайте знать!
Понял, нужно, чтобы если в CSV нет значения для любого из id-полей (airline_id, source_airport_id, destination_airport_id), либо там пусто/некорректное значение, скрипт должен выдавать ошибку и прерываться.
При этом остальные поля обрабатываем как раньше.
Вот исправленный скрипт с обязательной проверкой id-полей:
import csv
import json
import sys
def sanitize_value(val):
if val is None:
return ""
val = val.strip()
if val in {"\\N", "N/A", "-", ""}:
return ""
return val
def try_parse_int(val):
val = sanitize_value(val)
if val == "":
raise ValueError("Значение пустое")
try:
return int(val)
except ValueError:
raise ValueError(f"Невозможно преобразовать в int значение: {val}")
def csv_to_route_json(csv_file_path, json_file_path):
items = []
required_id_fields = ["airline_id", "source_airport_id", "destination_airport_id"]
with open(csv_file_path, encoding='utf-8-sig') as csv_file:
reader = csv.DictReader(csv_file)
for line_number, row in enumerate(reader, start=2): # 1 строка — заголовок
try:
airline = sanitize_value(row.get("airlines"))
airline_id_val = try_parse_int(row.get("airline_id"))
source_airport = sanitize_value(row.get("source_airport"))
source_airport_id_val = try_parse_int(row.get("source_airport_id"))
destination_airport = sanitize_value(row.get("destination_airport"))
destination_airport_id_val = try_parse_int(row.get("destination_airport_id"))
codeshare = sanitize_value(row.get("codeshare"))
stops_val = 0
if "stops" in row:
try:
stops_val = int(sanitize_value(row["stops"])) if sanitize_value(row["stops"]) != "" else 0
except ValueError:
raise ValueError(f"Некорректное значение stops: {row['stops']}")
equipment_name = sanitize_value(row.get("equipment"))
except ValueError as e:
print(f"Ошибка в строке {line_number}: {e}")
sys.exit(1)
airline_id = {
"$ref": "json_examples/json_instances/airlines.json",
"title": "Airline",
"0": {
"id": airline_id_val
}
}
source_airport_id = {
"$ref": "json_examples/json_instances/airports.json",
"title": "Airport",
"0": {
"id": source_airport_id_val
}
}
destination_airport_id = {
"$ref": "json_examples/json_instances/airports.json",
"title": "Airport",
"0": {
"id": destination_airport_id_val
}
}
equipment = {
"$ref": "json_examples/json_instances/planes.json",
"title": "Plane",
"0": {
"name": equipment_name
}
} if equipment_name != "" else ""
item = {
"airline": airline,
"airline_id": airline_id,
"source_airport": source_airport,
"source_airport_id": source_airport_id,
"destination_airport": destination_airport,
"destination_airport_id": destination_airport_id,
"codeshare": codeshare,
"stops": stops_val,
"equipment": equipment
}
items.append(item)
result = {
"$source": "",
"$schema": "",
"data": [
{
"$source": "",
"title": "Route",
"items": items
}
]
}
with open(json_file_path, "w", encoding="utf-8") as json_file:
json.dump(result, json_file, ensure_ascii=False, indent=4)
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Использование: python script.py input.csv output.json")
sys.exit(1)
csv_input = sys.argv[1]
json_output = sys.argv[2]
csv_to_route_json(csv_input, json_output)
print(f"Файл '{csv_input}' успешно преобразован в '{json_output}'")
Пояснения:
При отсутствии или неверном значении в любом из *_id полей будет выведено сообщение об ошибке с номером строки и скрипт прервётся.
При некорректном числе в поле stops — так же будет ошибка и выход.
Остальные поля обрабатываются как описано раньше.
Если хотите, могу помочь с тестированием и дальнейшими улучшениями.
Понял вашу точку. В предыдущем скрипте именно так и сделано — вложенный объект с ключом "0" содержит поле "id" именно в виде числа (integer).
Чтобы ещё раз подчеркнуть и показать полностью рабочий вариант с гарантией, что значения всех id полей внутри вложенных объектов — это int, ниже приведён итоговый скрипт с обязательной проверкой и конвертацией:
import csv
import json
import sys
def sanitize_value(val):
if val is None:
return ""
val = val.strip()
if val in {"\\N", "N/A", "-", ""}:
return ""
return val
def parse_int_or_fail(val, field_name, line_number):
val = sanitize_value(val)
if val == "":
raise ValueError(f"Пустое значение в обязательном поле {field_name} в строке {line_number}")
try:
return int(val)
except ValueError:
raise ValueError(f"Некорректное целочисленное значение '{val}' в поле {field_name} в строке {line_number}")
def csv_to_route_json(csv_file_path, json_file_path):
items = []
with open(csv_file_path, encoding='utf-8-sig') as csv_file:
reader = csv.DictReader(csv_file)
for line_number, row in enumerate(reader, start=2):
try:
airline = sanitize_value(row.get("airlines"))
airline_id_val = parse_int_or_fail(row.get("airline_id"), "airline_id", line_number)
source_airport = sanitize_value(row.get("source_airport"))
source_airport_id_val = parse_int_or_fail(row.get("source_airport_id"), "source_airport_id", line_number)
destination_airport = sanitize_value(row.get("destination_airport"))
destination_airport_id_val = parse_int_or_fail(row.get("destination_airport_id"), "destination_airport_id", line_number)
codeshare = sanitize_value(row.get("codeshare"))
stops_raw = row.get("stops")
stops_val = 0
if stops_raw is not None:
stops_str = sanitize_value(stops_raw)
if stops_str == "":
stops_val = 0
else:
try:
stops_val = int(stops_str)
except ValueError:
raise ValueError(f"Некорректное число в поле stops: '{stops_str}' в строке {line_number}")
else:
stops_val = 0
equipment_name = sanitize_value(row.get("equipment"))
except ValueError as e:
print(f"Ошибка: {e}")
sys.exit(1)
airline_id = {
"$ref": "json_examples/json_instances/airlines.json",
"title": "Airline",
"0": {
"id": airline_id_val # integer здесь
}
}
source_airport_id = {
"$ref": "json_examples/json_instances/airports.json",
"title": "Airport",
"0": {
"id": source_airport_id_val # integer здесь
}
}
destination_airport_id = {
"$ref": "json_examples/json_instances/airports.json",
"title": "Airport",
"0": {
"id": destination_airport_id_val # integer здесь
}
}
equipment = {
"$ref": "json_examples/json_instances/planes.json",
"title": "Plane",
"0": {
"name": equipment_name
}
} if equipment_name != "" else ""
item = {
"airline": airline,
"airline_id": airline_id,
"source_airport": source_airport,
"source_airport_id": source_airport_id,
"destination_airport": destination_airport,
"destination_airport_id": destination_airport_id,
"codeshare": codeshare,
"stops": stops_val,
"equipment": equipment
}
items.append(item)
result = {
"$source": "",
"$schema": "",
"data": [
{
"$source": "",
"title": "Route",
"items": items
}
]
}
with open(json_file_path, "w", encoding="utf-8") as json_file:
json.dump(result, json_file, ensure_ascii=False, indent=4)
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Использование: python script.py input.csv output.json")
sys.exit(1)
csv_input = sys.argv[1]
json_output = sys.argv[2]
csv_to_route_json(csv_input, json_output)
print(f"Файл '{csv_input}' успешно преобразован в '{json_output}'")
Итоги
Вложенные объекты с полями "id" — именно int.
Если id отсутствует или невалиден — выводится ошибка и скрипт завершает работу.
Все остальные поля — строки (согласно вашему требованию), а stops тоже гарантированно int (с дефолтом 0).
В выводе JSON все id — целые числа, а не строка.
Если нужно, помогу с примерами входа и выхода!
Понял задачу: если для любой из обязательных id-полей (airline_id, source_airport_id, destination_airport_id) в строке нет валидного integer — такую строку пропускаем (не добавляем в итоговый JSON), но не выдаём ошибку и не прекращаем работу.
Ниже исправленный скрипт с таким поведением:
import csv
import json
import sys
def sanitize_value(val):
if val is None:
return ""
val = val.strip()
if val in {"\\N", "N/A", "-", ""}:
return ""
return val
def parse_int(val):
val = sanitize_value(val)
if val == "":
return None
try:
return int(val)
except ValueError:
return None
def csv_to_route_json(csv_file_path, json_file_path):
items = []
with open(csv_file_path, encoding='utf-8-sig') as csv_file:
reader = csv.DictReader(csv_file)
for line_number, row in enumerate(reader, start=2):
airline = sanitize_value(row.get("airlines"))
airline_id_val = parse_int(row.get("airline_id"))
source_airport = sanitize_value(row.get("source_airport"))
source_airport_id_val = parse_int(row.get("source_airport_id"))
destination_airport = sanitize_value(row.get("destination_airport"))
destination_airport_id_val = parse_int(row.get("destination_airport_id"))
codeshare = sanitize_value(row.get("codeshare"))
stops_raw = row.get("stops")
equipment_name = sanitize_value(row.get("equipment"))
# Проверяем наличие всех обязательных id
if None in (airline_id_val, source_airport_id_val, destination_airport_id_val):
# Пропускаем эту строку
continue
# Обрабатываем stops
stops_val = 0
if stops_raw is not None:
stops_str = sanitize_value(stops_raw)
if stops_str == "":
stops_val = 0
else:
try:
stops_val = int(stops_str)
except ValueError:
stops_val = 0 # Можно и пропускать, но здесь просто 0
airline_id = {
"$ref": "json_examples/json_instances/airlines.json",
"title": "Airline",
"0": {
"id": airline_id_val
}
}
source_airport_id = {
"$ref": "json_examples/json_instances/airports.json",
"title": "Airport",
"0": {
"id": source_airport_id_val
}
}
destination_airport_id = {
"$ref": "json_examples/json_instances/airports.json",
"title": "Airport",
"0": {
"id": destination_airport_id_val
}
}
equipment = {
"$ref": "json_examples/json_instances/planes.json",
"title": "Plane",
"0": {
"name": equipment_name
}
} if equipment_name != "" else ""
item = {
"airline": airline,
"airline_id": airline_id,
"source_airport": source_airport,
"source_airport_id": source_airport_id,
"destination_airport": destination_airport,
"destination_airport_id": destination_airport_id,
"codeshare": codeshare,
"stops": stops_val,
"equipment": equipment
}
items.append(item)
result = {
"$source": "",
"$schema": "",
"data": [
{
"$source": "",
"title": "Route",
"items": items
}
]
}
with open(json_file_path, "w", encoding="utf-8") as json_file:
json.dump(result, json_file, ensure_ascii=False, indent=4)
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Использование: python script.py input.csv output.json")
sys.exit(1)
csv_input = sys.argv[1]
json_output = sys.argv[2]
csv_to_route_json(csv_input, json_output)
print(f"Файл '{csv_input}' успешно преобразован в '{json_output}'")
Ключевое изменение:
Если хотя бы в одном из id-полей нет валидного числа — строка пропускается.
Ошибок и выхода из программы не происходит.
Если надо, могу помочь с примером или дополнительными правками!
Понял, нужно при пропуске строки выводить информацию о том, какая строка была удалена (например, номер строки и краткая причина).
Вот обновлённый скрипт с выводом пропущенных строк в stderr:
import csv
import json
import sys
def sanitize_value(val):
if val is None:
return ""
val = val.strip()
if val in {"\\N", "N/A", "-", ""}:
return ""
return val
def parse_int(val):
val = sanitize_value(val)
if val == "":
return None
try:
return int(val)
except ValueError:
return None
def csv_to_route_json(csv_file_path, json_file_path):
items = []
with open(csv_file_path, encoding='utf-8-sig') as csv_file:
reader = csv.DictReader(csv_file)
for line_number, row in enumerate(reader, start=2):
airline = sanitize_value(row.get("airlines"))
airline_id_val = parse_int(row.get("airline_id"))
source_airport = sanitize_value(row.get("source_airport"))
source_airport_id_val = parse_int(row.get("source_airport_id"))
destination_airport = sanitize_value(row.get("destination_airport"))
destination_airport_id_val = parse_int(row.get("destination_airport_id"))
codeshare = sanitize_value(row.get("codeshare"))
stops_raw = row.get("stops")
equipment_name = sanitize_value(row.get("equipment"))
# Проверяем наличие всех обязательных id
missing_ids = []
if airline_id_val is None:
missing_ids.append("airline_id")
if source_airport_id_val is None:
missing_ids.append("source_airport_id")
if destination_airport_id_val is None:
missing_ids.append("destination_airport_id")
if missing_ids:
print(f"Строка {line_number} пропущена, отсутствуют или некорректны поля: {', '.join(missing_ids)}", file=sys.stderr)
continue
# Обрабатываем stops
stops_val = 0
if stops_raw is not None:
stops_str = sanitize_value(stops_raw)
if stops_str == "":
stops_val = 0
else:
try:
stops_val = int(stops_str)
except ValueError:
print(f"Строка {line_number}: некорректное значение stops '{stops_raw}', установлено 0", file=sys.stderr)
stops_val = 0
airline_id = {
"$ref": "json_examples/json_instances/airlines.json",
"title": "Airline",
"0": {
"id": airline_id_val
}
}
source_airport_id = {
"$ref": "json_examples/json_instances/airports.json",
"title": "Airport",
"0": {
"id": source_airport_id_val
}
}
destination_airport_id = {
"$ref": "json_examples/json_instances/airports.json",
"title": "Airport",
"0": {
"id": destination_airport_id_val
}
}
equipment = {
"$ref": "json_examples/json_instances/planes.json",
"title": "Plane",
"0": {
"name": equipment_name
}
} if equipment_name != "" else ""
item = {
"airline": airline,
"airline_id": airline_id,
"source_airport": source_airport,
"source_airport_id": source_airport_id,
"destination_airport": destination_airport,
"destination_airport_id": destination_airport_id,
"codeshare": codeshare,
"stops": stops_val,
"equipment": equipment
}
items.append(item)
result = {
"$source": "",
"$schema": "",
"data": [
{
"$source": "",
"title": "Route",
"items": items
}
]
}
with open(json_file_path, "w", encoding="utf-8") as json_file:
json.dump(result, json_file, ensure_ascii=False, indent=4)
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Использование: python script.py input.csv output.json")
sys.exit(1)
csv_input = sys.argv[1]
json_output = sys.argv[2]
csv_to_route_json(csv_input, json_output)
print(f"Файл '{csv_input}' успешно преобразован в '{json_output}'")
Что добавлено:
Если пропускаем строку из-за отсутствия/некорректности id — выводим на stderr (то есть в консоль) ее номер и какие id отсутствуют.
Если stops плохое — выводим предупреждение, ставим 0.
Так вы сразу увидите, какие строки не попали в результат.
для типа Airlines у которого есть атрибуты (это пример реального обьекта, а мне нужна схема, как сверху, с описаниями и типами): "id": 21317,
"name": "Svyaz Rossiya",
"alias": "Russian Commuter",
"IATA": "7R",
"ICAO": "SJM",
"callsign": "RussianConnecty",
"country": {
"$ref": "json_examples/json_instances/countries.json",
"title": "Country",
"0": {
"name": "Russia"
}
},
"active ": "Y"
Пояснения:
Поле country — объект, ссылается через $ref на отдельную схему страны (как в вашем примере).
Все строки имеют тип "string".
id — число целочисленного типа.
Добавлен блок "meta" с ключом id.
В "namespace" укажите ваш актуальный неймспейс.
Описание полей основано на вашем примере.
Если хотите — могу помочь с генерацией этой схемы из Python или более подробным описанием!
Пояснения:
latitude, longitude, altitude имеют тип "number".
Поле country — объект, ссылающийся на схему страны через $ref.
Все строки имеют тип "string".
id — целое число.
Сохранён namespace "Mephi.Cybernetics.Race.Core.Tests", как вы и просили.
Если нужно, могу помочь с другими схемами!
{
"$source": "",
"type": "object",
"title": "Airport",
"namespace": "Mephi.Cybernetics.Race.Core.Tests",
"properties": {
"id": {
"type": "integer",
"description": "Unique identifier of the airport"
},
"name": {
"type": "string",
"description": "Name of the airport"
},
"city": {
"type": "string",
"description": "City where the airport is located"
},
"country": {
"type": "object",
"$ref": "json_examples/json_instances/countries.json",
"title": "Country",
"description": "Country of the airport"
},
"IATA": {
"type": "string",
"description": "IATA airport code"
},
"ICAO": {
"type": "string",
"description": "ICAO airport code"
},
"latitude": {
"type": "long",
"description": "Latitude coordinate of the airport"
},
"longitude": {
"type": "long",
"description": "Longitude coordinate of the airport"
},
"altitude": {
"type": "long",
"description": "Altitude of the airport (in feet)"
},
"timezone": {
"type": "string",
"description": "Timezone abbreviation"
},
"DST": {
"type": "string",
"description": "Daylight saving time status"
},
"tz_database_timezone": {
"type": "string",
"description": "Timezone in tz database format"
},
"type": {
"type": "string",
"description": "Type of the airport"
},
"source": {
"type": "string",
"description": "Source of the airport data"
}
},
"meta": {
"keys": {
"id": "id"
}
}
}
Обычно long — целый числовой тип. Если ваше описание схемы допускает использование long для координат с плавающей точкой — всё ок.
Если нужно — могу помочь заменить на double или иные варианты.
Если есть еще что-то — дайте знать!
Вот пример JSON-схемы для вашего объекта типа "Route" с учетом вложенных ссылок и описаний для каждого поля: