Skip to content

Commit a9c8c6f

Browse files
lemireTheLartians
andauthored
Adding simdjson example (#516)
* Adding simdjson example * Update README.md Co-authored-by: Lars Melchior <TheLartians@users.noreply.github.com> * cmake format --------- Co-authored-by: Lars Melchior <TheLartians@users.noreply.github.com>
1 parent 2fa4837 commit a9c8c6f

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

examples/simdjson/CMakeLists.txt

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
cmake_minimum_required(VERSION 3.14 FATAL_ERROR)
2+
3+
project(CPMSIMDJSONExample)
4+
5+
# ---- Dependencies ----
6+
7+
include(../../cmake/CPM.cmake)
8+
CPMAddPackage("gh:simdjson/simdjson@3.5.0")
9+
10+
# ---- Executable ----
11+
12+
add_executable(CPMSIMDJSONExample main.cpp)
13+
target_compile_features(CPMSIMDJSONExample PRIVATE cxx_std_17)
14+
target_link_libraries(CPMSIMDJSONExample simdjson::simdjson)

examples/simdjson/main.cpp

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#include <iostream>
2+
3+
#include "simdjson.h"
4+
using namespace simdjson;
5+
6+
int main() {
7+
ondemand::parser parser;
8+
auto cars_json = R"( [
9+
{ "make": "Toyota", "model": "Camry", "year": 2018, "tire_pressure": [ 40.1, 39.9, 37.7, 40.4 ] },
10+
{ "make": "Kia", "model": "Soul", "year": 2012, "tire_pressure": [ 30.1, 31.0, 28.6, 28.7 ] },
11+
{ "make": "Toyota", "model": "Tercel", "year": 1999, "tire_pressure": [ 29.8, 30.0, 30.2, 30.5 ] }
12+
] )"_padded;
13+
14+
// Iterating through an array of objects
15+
for (ondemand::object car : parser.iterate(cars_json)) {
16+
// Accessing a field by name
17+
std::cout << "Make/Model: " << std::string_view(car["make"]) << "/"
18+
<< std::string_view(car["model"]) << std::endl;
19+
20+
// Casting a JSON element to an integer
21+
uint64_t year = car["year"];
22+
std::cout << "- This car is " << 2020 - year << " years old." << std::endl;
23+
24+
// Iterating through an array of floats
25+
double total_tire_pressure = 0;
26+
for (double tire_pressure : car["tire_pressure"]) {
27+
total_tire_pressure += tire_pressure;
28+
}
29+
std::cout << "- Average tire pressure: " << (total_tire_pressure / 4) << std::endl;
30+
}
31+
}

0 commit comments

Comments
 (0)