Skip to content

Can't throw exception when starting file is a number #1649

@h3x4n1um

Description

@h3x4n1um
  • What is the issue you have?

When parsing binary file, if several first bytes of file is number, the json parser not throw an exception

  • Please describe the steps to reproduce the issue. Can you provide a small but working code example?

The below example show that it recognize fake_undetected.json file is a json file

#include <filesystem>
#include <fstream>
#include <iomanip>
#include <iostream>

#include "json.hpp"

int main(){
    std::ifstream input;
    std::ofstream output;
    nlohmann::json js;
    int test = 2019;

    //create real json
    output.open("real.json");
    js["Hello"] = "Hi";
    js["Year"] = test;
    output << std::setw(4) << js;
    output.close();

    //create detected fake json file
    output.open("fake_detected.json", std::ofstream::binary);
    output.write(reinterpret_cast <const char*> (&test), sizeof test);
    output.close();

    //create undetected fake json file
    output.open("fake_undetected.json", std::ofstream::binary);
    output << test;
    output.write(reinterpret_cast <const char*> (&test), sizeof test);
    output.close();

    //verify json
    std::filesystem::path p = std::filesystem::current_path();
    for (auto &file : std::filesystem::recursive_directory_iterator(p)){
        if (std::filesystem::is_regular_file(file.path())){
            input.open(file.path());
            try{
                input >> js;
                std::cout << file.path() << " is a json" << std::endl;
            }
            catch(nlohmann::json::exception &e){
                std::cerr << file.path() << " is not a json" << std::endl;
            }
            input.close();
        }
    }
    return 0;
}
  • What is the expected behavior?

It should throw nlohmann::json::exception when parse fake_undetected.json

  • And what is the actual behavior instead?

Opposite above

I use GCC 9.0 (MSYS2 with MinGW-w64 package) and compile using

g++ -lstdc++fs -std=c++17 -c test.cpp -o test.o
  • Did you use a released version of the library or the version from the develop branch?

I use released version 3.6.1 of the library

Hello, world!

Metadata

Metadata

Assignees

No one assigned

    Labels

    kind: bugsolution: proposed fixa fix for the issue has been proposed and waits for confirmation

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions