wttr/src/render/Json.zig

54 lines
1.7 KiB
Zig

const std = @import("std");
const types = @import("../weather/types.zig");
pub fn render(writer: *std.Io.Writer, weather: types.WeatherData) !void {
const data = .{
.current_condition = .{
.temp_C = weather.current.temp_c,
.weatherCode = weather.current.weather_code,
.weatherDesc = .{.{ .value = weather.current.condition }},
.humidity = weather.current.humidity,
.windspeedKmph = weather.current.wind_kph,
.winddirDegree = weather.current.wind_deg,
.pressure = weather.current.pressure_mb,
.precipMM = weather.current.precip_mm,
},
.weather = weather.forecast,
};
try writer.print("{f}", .{std.json.fmt(data, .{})});
}
test "render json format" {
const allocator = std.testing.allocator;
const weather = types.WeatherData{
.location = "London",
.coords = .{ .latitude = 0, .longitude = 0 },
.current = .{
.temp_c = 15.0,
.feels_like_c = 15.0,
.condition = "Partly cloudy",
.weather_code = .clouds_few,
.humidity = 72,
.wind_kph = 13.0,
.wind_deg = 225.0,
.pressure_mb = 1013.0,
.precip_mm = 0.0,
.visibility_km = null,
},
.forecast = &[_]types.ForecastDay{},
.allocator = allocator,
};
var output_buf: [4096]u8 = undefined;
var writer = std.Io.Writer.fixed(&output_buf);
try render(&writer, weather);
const output = output_buf[0..writer.end];
try std.testing.expect(output.len > 0);
try std.testing.expect(std.mem.indexOf(u8, output, "temp_C") != null);
try std.testing.expect(std.mem.indexOf(u8, output, "15") != null);
}