I have a json file that I want to read in as a string, the problem I'm having is the read() function reads the first line like so:
json file contents:
{
"structure": [
{
"thing1": "1441",
"thing2": 1234,
"thing3": "2200.685715",
"thing4": "1793.190430",
}
}
what gets read is just the leading {
(the first record/line), so when I print out I get this at the beginning and a whole bunch of blank spaces. How do I read in all the records/lines as a single pre-allocated string?
my code:
open (unit=11, status='scratch', access='stream', form='formatted')
call jsonHandler%print(outputJson, 11)
rewind(11)
inquire(11, SIZE=file_size)
! allocate the output based on the size of the file
allocate(character(len=file_size)::output)
read(11, *) output
close(11)
notes on the code:
I am using Jacob Williams' json-fortran library and I am aware that there is a serialize() function, however this is a very slow algorithm, because of the appends, this is the solution I came up with to have a pre-allocated string, and therefore will be fast
I am writing to a temporary file so normally this file object would not show up on the file system, the goal of this is to use a file objects powerful functionality without writing to the file system
This is more of a generalization of how to read multi-record data into a string, I am simply using json as an example
Do not use form="formatted"
. You do not want the formatting in the file to be interpretted in any way when reading the file content.