Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

JSON extension



  • Hi,
    is it normal / safe practice to save/load json files without extension (.json) ?

    QFile jsonFile("file");
       if(jsonFile.open(QFile::ReadOnly)){
    
          QJsonDocument jrampe(QJsonDocument::fromJson(jsonFile.readAll()));
          QJsonArray toolArr = jrampe.array();
    ..
    

    Thanks



  • @LeLev
    If you wish/prefer to save the file without .json extension, that's OK, there is no law against it! In itself it certainly won't interfere with your ability to read it back in and parse as JSON.



  • @LeLev
    What do you mean? It's up to you what extension you put on a file. .json would be a reasonable choice, but it's not compulsory. (It certainly won't matter to Qt/QFile.) Since here you are reading an existing file, you don't have choice, it's whatever name it was saved under.

    Whether it has an extension or not --- e.g. if you try to read a non- .json and it turns out it is not a JSON doc in the first place --- you may get failure. https://doc.qt.io/qt-5/qjsondocument.html#fromJson

    Returns a valid (non-null) QJsonDocument if the parsing succeeds. If it fails, the returned document will be null, and the optional error variable will contain further details about the error.

    You need to test for this (in all cases).

    Personally I do save JSON docs as .json, so I know what's going on.



  • @JonB said in JSON extension:

    What do you mean?

    sorry i forgot to specify : i want to save the file without any extension.

    please let me explain : its just for convenience,
    my user will enter informations, then i will construct objects with his input and save in json format. I want him to enter the file name also but not the extension!

    so i do :

    void saveFile(QString filename){
     
      QFile jsonFile(fileName+".json")
    }
    

    Then the user can load his saved files.

    And for loading the file, i show a listView with fileNames for my user
    and i have to write this to hide extension

    function noExtension(fileName){
         return fileName.substring(0,fileName.lastIndexOf("."))
     }
    

    because its usless to show the extension to my user..
    this is why i wanted to simply save the file with no extension.



  • @LeLev
    If you wish/prefer to save the file without .json extension, that's OK, there is no law against it! In itself it certainly won't interfere with your ability to read it back in and parse as JSON.



  • ok thank you @JonB


Log in to reply