用扩展包json-fortran读取json文件
说明:没啥好说的,就是用扩展包json-fortran读取json文件到fortran代码
一、扩展包json-fortran获取
- 首先获取源码,Download zip即可。
- 解压文件,得到解压后的文件如下
- 将源码编译成库的方式有几种,包括build.sh脚本,A FoBiS configuration file , Visual Studio工程,cmake,FPM。
此处采用Visual Studio工程进行编译。具体查看github上说明。 - 欲编译fortran文件,必须先在vs中,添加单个组件,fortran。vs2022好像不支持fortran,因此采用vs2019进行编译。
- 源码根目录找到 visual_studio文件夹,用vs2019打开其中 jsonfortran.sln。先生成 jsonfortranlib项目,然后生成测试项目jsonfortrantest。生成的库文件在 json-fortran-8.3.0\lib\x64文件夹中(版本和平台根据自己实际情况有不同),库名字叫libjsonfortrand.lib。后续需要的库都在这个文件夹中。
二、使用json-fortran读取Json文件
- 在vs2019中新建fortran空项目。
- 源文件中,添加测试文件test.f90,内容如下:
program example1
use json_module
implicit none
type(json_file) :: json
logical :: found,m
integer :: i,j,k
character(len=:),allocatable :: str
! initialize the class
call json%initialize()
! read the file
call json%load(filename = 'E:/openSourceCode/json-fortran/json-fortran-8.3.0/files/inputs/test1.json')
! print the file to the console
call json%print()
! extract data from the file
! [found can be used to check if the data was really there]
call json%get('version.major', i, found)
if ( .not. found ) stop 1
call json%get('version.minor', j, found)
if ( .not. found ) stop 1
call json%get('data(1).number', k, found)
if ( .not. found ) stop 1
call json%get('data(1).tf1', m, found)
if ( .not. found ) stop 1
write(*,*) '======',m
call json%get('data(1).name', str, found)
if ( .not. found ) stop 1
write(*,*) 'str ======',str
! clean up
call json%destroy()
if (json%failed()) stop 1
pause
end program example1
代码中包含了读取json文件整个输出和提取其中特定的顺序。注意字符串的读取用 character(len=:),allocatable :: str格式。
其中,待读取的文件test1.json的内容如下:
{
"version": {
"major": 2,
"minor": 2,
"patch": 1,
"string": "2.2.1",
"svn": 7191
},
"files": [
"..\\path\\to\\files\\file1.txt",
"..\\path\\to\\files\\file2.txt",
"..\\path\\to\\files\\file3.txt",
"test \u2FA4 \uABCD \uABCD\uABCDtest",
" test \\u \" blah\\\" test test",
"..\\path\\to\\files\\",
"\\"
],
"a": {
"b": 1
},
"escape": " \" \\ \/ \b \f \n \r \t ",
"empty_array": [],
"empty_object": {},
"empty_string": "",
"data": [{
"number": 1,
"tf1": true,
"tf2": false,
"empty": null,
"name": "Horatio",
"array": [
"1",
"2",
"3"
]
}, {
"number": 2,
"integer": 33,
"real": 0.2333000000000000E+003,
"name": "Nelson"
}],
"rfc6901 tests": {
"foo": ["bar", "baz"],
" ": 0,
"a/b": 1,
"c%d": 2,
"e^f": 3,
"g|h": 4,
"i\\j": 5,
"k\"l": 6,
" ": 7,
"m~n": 8
}
}
记得改路径。
- 修改项目附加依赖项(导入json-fortran库)
3.1 所有要修改的路径都指向生成的库:本处debugLib为生成的json-fortran-8.3.0\lib\x64文件夹的拷贝。
!这里插入图片描述](https://img-blog.csdnimg.cn/0d3a63643856460581eecfb199987275.png)
修改如上三处即可。