Fortran For Fun 函数库之json-fortran

json(JaveScript Object Notation)和XML都是一种数据交换格式,采用完全独立于编程语言的文本格式来存储和表示数据。json数据可以存储任意数据类型,结构简洁清晰,易于编写和阅读。

json_fortran是一个完全采用fortran语言编写的json API,基本上可以实现json文件的读写。

learn_json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
program learn_json
use json_module
implicit none
character(len=*),parameter :: filename = 'test.json'
type(json_value),pointer :: p1,p2
type(json_core) :: json !! factory for manipulating `json_value` pointers
integer :: iunit
integer, parameter :: is = 1, &
iv(*) = [1,2,3,4]
real, parameter :: rs = 1.0, &
rv(*) = [1.,2.,3.,4.]
character(*), parameter :: case = 'test'
call json%initialize()
!root:
call json%create_object(p1,filename) ! create the value and associate the pointer
!> case
call json%add(p1,'case',case)
!> integer
call json%create_object(p2,"integer")
call json%add(p2,"scalar",is)
call json%add(p2,"vector",iv)
call json%add(p2,"descreption","integer data")
call json%add(p1,p2)
nullify(p2)
!> real
call json%create_object(p2,"real")
call json%add(p2,"scalar",rs)
call json%add(p2,"vector",rv)
call json%add(p2,"descreption","real data")
call json%add(p1,p2)
nullify(p2)
!> create file
open(newunit=iunit, file=filename, status='replace')
call json%print(p1,iunit)
close(iunit)
nullify(p1)
end program learn_json

结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
"case": "test",
"integer": {
"scalar": 1,
"vector": [
1,
2,
3,
4
],
"descreption": "integer data"
},
"real": {
"scalar": 0.1E+1,
"vector": [
0.1E+1,
0.2E+1,
0.3E+1,
0.4E+1
],
"descreption": "real data"
}
}