jacobwilliams / json-fortran

A Modern Fortran JSON API
https://jacobwilliams.github.io/json-fortran/
Other
333 stars 83 forks source link

Print only a single JSON field #468

Closed nyckmaia closed 4 years ago

nyckmaia commented 4 years ago

This is a simple JSON example:

{
    "scalar": 1.0
    "array": [
        {
            "x": 0,
            "y": 0,
        },
        {
            "x": 1,
            "y": 1,
        }
    ]
}

I would like to print in the console just a single field of this JSON, like:

! Not working notation:
call json%print("$['array'][2]")

The console output should be:

{
    "x": 1,
    "y": 1,
}

How can I do it?

jacobwilliams commented 4 years ago

note that your JSON has some typos. But the basic idea to do this is to get the element you want as a JSON pointer, and then you can print only that. Like so:

    type(json_core) :: json
    type(json_value), pointer :: p
    type(json_file) :: jsonf
    character(kind=json_CDK,len=:),allocatable :: jfstring
    character(kind=CK,len=1), parameter :: nl = new_line(CK_" ")

    jfstring = '{'//nl//&
                '    "scalar": 1.0,'//nl//&
                '    "array": ['//nl//&
                '        {'//nl//&
                '            "x": 0,'//nl//&
                '            "y": 0'//nl//&
                '        },'//nl//&
                '        {'//nl//&
                '            "x": 1,'//nl//&
                '            "y": 1'//nl//&
                '        }'//nl//&
                '    ]'//nl//&
                '}'//nl

    call jsonf%initialize(path_mode=3)
    call jsonf%deserialize(jfstring)

    call jsonf%get(CK_"$['array'][2]", p)

    call json%print(p)

Result is:

{
  "x": 1,
  "y": 1
}
nyckmaia commented 4 years ago

Thank you @jacobwilliams !

Last doubt: In the line:

call jsonf%get(CK_"$['array'][2]", p)

What is this CK_ prefix? I saw it on the library examples, but I couldn't understand it.

jacobwilliams commented 4 years ago

CK_'string' is just specifying the character kind of the string. CK being a variable exported by the library. If you are not compiling the library with unicode support, then CK is just the default kind (same as declaring strings without it).