File: ogrgeojsonutils.cpp

package info (click to toggle)
gdal 3.11.3%2Bdfsg-1~exp1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 89,016 kB
  • sloc: cpp: 1,165,048; ansic: 208,864; python: 26,958; java: 5,972; xml: 4,611; sh: 3,776; cs: 2,508; yacc: 1,306; makefile: 213
file content (1141 lines) | stat: -rw-r--r-- 38,527 bytes parent folder | download | duplicates (2)
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
/******************************************************************************
 *
 * Project:  OpenGIS Simple Features Reference Implementation
 * Purpose:  Implementation of private utilities used within OGR GeoJSON Driver.
 * Author:   Mateusz Loskot, mateusz@loskot.net
 *
 ******************************************************************************
 * Copyright (c) 2007, Mateusz Loskot
 * Copyright (c) 2010-2013, Even Rouault <even dot rouault at spatialys.com>
 *
 * SPDX-License-Identifier: MIT
 ****************************************************************************/

#include "ogrgeojsonutils.h"
#include <assert.h>
#include "cpl_port.h"
#include "cpl_conv.h"
#include "cpl_json_streaming_parser.h"
#include "ogr_geometry.h"
#include <json.h>  // JSON-C

#include <algorithm>
#include <memory>

const char szESRIJSonFeaturesGeometryRings[] =
    "{\"features\":[{\"geometry\":{\"rings\":[";

// Cf https://github.com/OSGeo/gdal/issues/9996#issuecomment-2129845692
const char szESRIJSonFeaturesAttributes[] = "{\"features\":[{\"attributes\":{";

/************************************************************************/
/*                           SkipUTF8BOM()                              */
/************************************************************************/

static void SkipUTF8BOM(const char *&pszText)
{
    /* Skip UTF-8 BOM (#5630) */
    const GByte *pabyData = reinterpret_cast<const GByte *>(pszText);
    if (pabyData[0] == 0xEF && pabyData[1] == 0xBB && pabyData[2] == 0xBF)
        pszText += 3;
}

/************************************************************************/
/*                           IsJSONObject()                             */
/************************************************************************/

static bool IsJSONObject(const char *pszText)
{
    if (nullptr == pszText)
        return false;

    SkipUTF8BOM(pszText);

    /* -------------------------------------------------------------------- */
    /*      This is a primitive test, but we need to perform it fast.       */
    /* -------------------------------------------------------------------- */
    while (*pszText != '\0' && isspace(static_cast<unsigned char>(*pszText)))
        pszText++;

    const char *const apszPrefix[] = {"loadGeoJSON(", "jsonp("};
    for (size_t iP = 0; iP < sizeof(apszPrefix) / sizeof(apszPrefix[0]); iP++)
    {
        if (strncmp(pszText, apszPrefix[iP], strlen(apszPrefix[iP])) == 0)
        {
            pszText += strlen(apszPrefix[iP]);
            break;
        }
    }

    if (*pszText != '{')
        return false;

    return true;
}

/************************************************************************/
/*                           GetTopLevelType()                          */
/************************************************************************/

static std::string GetTopLevelType(const char *pszText)
{
    if (!strstr(pszText, "\"type\""))
        return std::string();

    SkipUTF8BOM(pszText);

    struct MyParser : public CPLJSonStreamingParser
    {
        std::string m_osLevel{};
        bool m_bInTopLevelType = false;
        std::string m_osTopLevelTypeValue{};

        void StartObjectMember(const char *pszKey, size_t nLength) override
        {
            m_bInTopLevelType = false;
            if (nLength == strlen("type") && strcmp(pszKey, "type") == 0 &&
                m_osLevel == "{")
            {
                m_bInTopLevelType = true;
            }
        }

        void String(const char *pszValue, size_t nLength) override
        {
            if (m_bInTopLevelType)
            {
                m_osTopLevelTypeValue.assign(pszValue, nLength);
                StopParsing();
            }
        }

        void StartObject() override
        {
            m_osLevel += '{';
            m_bInTopLevelType = false;
        }

        void EndObject() override
        {
            if (!m_osLevel.empty())
                m_osLevel.pop_back();
            m_bInTopLevelType = false;
        }

        void StartArray() override
        {
            m_osLevel += '[';
            m_bInTopLevelType = false;
        }

        void EndArray() override
        {
            if (!m_osLevel.empty())
                m_osLevel.pop_back();
            m_bInTopLevelType = false;
        }
    };

    MyParser oParser;
    oParser.Parse(pszText, strlen(pszText), true);
    return oParser.m_osTopLevelTypeValue;
}

/************************************************************************/
/*                           GetCompactJSon()                           */
/************************************************************************/

static CPLString GetCompactJSon(const char *pszText, size_t nMaxSize)
{
    /* Skip UTF-8 BOM (#5630) */
    const GByte *pabyData = reinterpret_cast<const GByte *>(pszText);
    if (pabyData[0] == 0xEF && pabyData[1] == 0xBB && pabyData[2] == 0xBF)
        pszText += 3;

    CPLString osWithoutSpace;
    bool bInString = false;
    for (int i = 0; pszText[i] != '\0' && osWithoutSpace.size() < nMaxSize; i++)
    {
        if (bInString)
        {
            if (pszText[i] == '\\')
            {
                osWithoutSpace += pszText[i];
                if (pszText[i + 1] == '\0')
                    break;
                osWithoutSpace += pszText[i + 1];
                i++;
            }
            else if (pszText[i] == '"')
            {
                bInString = false;
                osWithoutSpace += '"';
            }
            else
            {
                osWithoutSpace += pszText[i];
            }
        }
        else if (pszText[i] == '"')
        {
            bInString = true;
            osWithoutSpace += '"';
        }
        else if (!isspace(static_cast<unsigned char>(pszText[i])))
        {
            osWithoutSpace += pszText[i];
        }
    }
    return osWithoutSpace;
}

/************************************************************************/
/*                          IsGeoJSONLikeObject()                       */
/************************************************************************/

static bool IsGeoJSONLikeObject(const char *pszText, bool &bMightBeSequence,
                                bool &bReadMoreBytes, GDALOpenInfo *poOpenInfo,
                                const char *pszExpectedDriverName)
{
    bMightBeSequence = false;
    bReadMoreBytes = false;

    if (!IsJSONObject(pszText))
        return false;

    const std::string osTopLevelType = GetTopLevelType(pszText);
    if (osTopLevelType == "Topology")
        return false;

    if (poOpenInfo->IsSingleAllowedDriver(pszExpectedDriverName) &&
        GDALGetDriverByName(pszExpectedDriverName))
    {
        return true;
    }

    if ((!poOpenInfo->papszAllowedDrivers ||
         CSLFindString(poOpenInfo->papszAllowedDrivers, "JSONFG") >= 0) &&
        GDALGetDriverByName("JSONFG") && JSONFGIsObject(pszText, poOpenInfo))
    {
        return false;
    }

    if (osTopLevelType == "FeatureCollection")
    {
        return true;
    }

    const std::string osWithoutSpace = GetCompactJSon(pszText, strlen(pszText));
    if (osWithoutSpace.find("{\"features\":[") == 0 &&
        osWithoutSpace.find(szESRIJSonFeaturesGeometryRings) != 0 &&
        osWithoutSpace.find(szESRIJSonFeaturesAttributes) != 0)
    {
        return true;
    }

    // See
    // https://raw.githubusercontent.com/icepack/icepack-data/master/meshes/larsen/larsen_inflow.geojson
    // "{"crs":...,"features":[..."
    // or
    // https://gist.githubusercontent.com/NiklasDallmann/27e339dd78d1942d524fbcd179f9fdcf/raw/527a8319d75a9e29446a32a19e4c902213b0d668/42XR9nLAh8Poh9Xmniqh3Bs9iisNm74mYMC56v3Wfyo=_isochrones_fails.geojson
    // "{"bbox":...,"features":[..."
    if (osWithoutSpace.find(",\"features\":[") != std::string::npos)
    {
        return !ESRIJSONIsObject(pszText, poOpenInfo);
    }

    // See https://github.com/OSGeo/gdal/issues/2720
    if (osWithoutSpace.find("{\"coordinates\":[") == 0 ||
        // and https://github.com/OSGeo/gdal/issues/2787
        osWithoutSpace.find("{\"geometry\":{\"coordinates\":[") == 0 ||
        // and https://github.com/qgis/QGIS/issues/61266
        osWithoutSpace.find(
            "{\"geometry\":{\"type\":\"Point\",\"coordinates\":[") == 0 ||
        osWithoutSpace.find(
            "{\"geometry\":{\"type\":\"LineString\",\"coordinates\":[") == 0 ||
        osWithoutSpace.find(
            "{\"geometry\":{\"type\":\"Polygon\",\"coordinates\":[") == 0 ||
        osWithoutSpace.find(
            "{\"geometry\":{\"type\":\"MultiPoint\",\"coordinates\":[") == 0 ||
        osWithoutSpace.find(
            "{\"geometry\":{\"type\":\"MultiLineString\",\"coordinates\":[") ==
            0 ||
        osWithoutSpace.find(
            "{\"geometry\":{\"type\":\"MultiPolygon\",\"coordinates\":[") ==
            0 ||
        osWithoutSpace.find("{\"geometry\":{\"type\":\"GeometryCollection\","
                            "\"geometries\":[") == 0)
    {
        return true;
    }

    if (osTopLevelType == "Feature" || osTopLevelType == "Point" ||
        osTopLevelType == "LineString" || osTopLevelType == "Polygon" ||
        osTopLevelType == "MultiPoint" || osTopLevelType == "MultiLineString" ||
        osTopLevelType == "MultiPolygon" ||
        osTopLevelType == "GeometryCollection")
    {
        bMightBeSequence = true;
        return true;
    }

    // See https://github.com/OSGeo/gdal/issues/3280
    if (osWithoutSpace.find("{\"properties\":{") == 0)
    {
        bMightBeSequence = true;
        bReadMoreBytes = true;
        return false;
    }

    return false;
}

static bool IsGeoJSONLikeObject(const char *pszText, GDALOpenInfo *poOpenInfo,
                                const char *pszExpectedDriverName)
{
    bool bMightBeSequence;
    bool bReadMoreBytes;
    return IsGeoJSONLikeObject(pszText, bMightBeSequence, bReadMoreBytes,
                               poOpenInfo, pszExpectedDriverName);
}

/************************************************************************/
/*                       ESRIJSONIsObject()                             */
/************************************************************************/

bool ESRIJSONIsObject(const char *pszText, GDALOpenInfo *poOpenInfo)
{
    if (!IsJSONObject(pszText))
        return false;

    if (poOpenInfo->IsSingleAllowedDriver("ESRIJSON") &&
        GDALGetDriverByName("ESRIJSON"))
    {
        return true;
    }

    if (  // ESRI Json geometry
        (strstr(pszText, "\"geometryType\"") != nullptr &&
         strstr(pszText, "\"esriGeometry") != nullptr)

        // ESRI Json "FeatureCollection"
        || strstr(pszText, "\"fieldAliases\"") != nullptr

        // ESRI Json "FeatureCollection"
        || (strstr(pszText, "\"fields\"") != nullptr &&
            strstr(pszText, "\"esriFieldType") != nullptr))
    {
        return true;
    }

    const std::string osWithoutSpace = GetCompactJSon(pszText, strlen(pszText));
    if (osWithoutSpace.find(szESRIJSonFeaturesGeometryRings) == 0 ||
        osWithoutSpace.find(szESRIJSonFeaturesAttributes) == 0 ||
        osWithoutSpace.find("\"spatialReference\":{\"wkid\":") !=
            std::string::npos)
    {
        return true;
    }

    return false;
}

/************************************************************************/
/*                       TopoJSONIsObject()                             */
/************************************************************************/

bool TopoJSONIsObject(const char *pszText, GDALOpenInfo *poOpenInfo)
{
    if (!IsJSONObject(pszText))
        return false;

    if (poOpenInfo->IsSingleAllowedDriver("TopoJSON") &&
        GDALGetDriverByName("TopoJSON"))
    {
        return true;
    }

    return GetTopLevelType(pszText) == "Topology";
}

/************************************************************************/
/*                      IsLikelyNewlineSequenceGeoJSON()                */
/************************************************************************/

static GDALIdentifyEnum
IsLikelyNewlineSequenceGeoJSON(VSILFILE *fpL, const GByte *pabyHeader,
                               const char *pszFileContent)
{
    const size_t nBufferSize = 4096 * 10;
    std::vector<GByte> abyBuffer;
    abyBuffer.resize(nBufferSize + 1);

    int nCurlLevel = 0;
    bool bInString = false;
    bool bLastIsEscape = false;
    bool bFirstIter = true;
    bool bEOLFound = false;
    int nCountObject = 0;
    while (true)
    {
        size_t nRead;
        bool bEnd = false;
        if (bFirstIter)
        {
            const char *pszText =
                pszFileContent ? pszFileContent
                               : reinterpret_cast<const char *>(pabyHeader);
            assert(pszText);
            nRead = std::min(strlen(pszText), nBufferSize);
            memcpy(abyBuffer.data(), pszText, nRead);
            bFirstIter = false;
            if (fpL)
            {
                VSIFSeekL(fpL, nRead, SEEK_SET);
            }
        }
        else
        {
            nRead = VSIFReadL(abyBuffer.data(), 1, nBufferSize, fpL);
            bEnd = nRead < nBufferSize;
        }
        for (size_t i = 0; i < nRead; i++)
        {
            if (nCurlLevel == 0)
            {
                if (abyBuffer[i] == '{')
                {
                    nCountObject++;
                    if (nCountObject == 2)
                    {
                        break;
                    }
                    nCurlLevel++;
                }
                else if (nCountObject == 1 && abyBuffer[i] == '\n')
                {
                    bEOLFound = true;
                }
                else if (!isspace(static_cast<unsigned char>(abyBuffer[i])))
                {
                    return GDAL_IDENTIFY_FALSE;
                }
            }
            else if (bInString)
            {
                if (bLastIsEscape)
                {
                    bLastIsEscape = false;
                }
                else if (abyBuffer[i] == '\\')
                {
                    bLastIsEscape = true;
                }
                else if (abyBuffer[i] == '"')
                {
                    bInString = false;
                }
            }
            else if (abyBuffer[i] == '"')
            {
                bInString = true;
            }
            else if (abyBuffer[i] == '{')
            {
                nCurlLevel++;
            }
            else if (abyBuffer[i] == '}')
            {
                nCurlLevel--;
            }
        }
        if (!fpL || bEnd || nCountObject == 2)
            break;
    }
    if (bEOLFound && nCountObject == 2)
        return GDAL_IDENTIFY_TRUE;
    return GDAL_IDENTIFY_UNKNOWN;
}

/************************************************************************/
/*                           GeoJSONFileIsObject()                      */
/************************************************************************/

static bool GeoJSONFileIsObject(GDALOpenInfo *poOpenInfo)
{
    // By default read first 6000 bytes.
    // 6000 was chosen as enough bytes to
    // enable all current tests to pass.

    if (poOpenInfo->fpL == nullptr || !poOpenInfo->TryToIngest(6000))
    {
        return false;
    }

    bool bMightBeSequence = false;
    bool bReadMoreBytes = false;
    if (!IsGeoJSONLikeObject(
            reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
            bMightBeSequence, bReadMoreBytes, poOpenInfo, "GeoJSON"))
    {
        if (!(bReadMoreBytes && poOpenInfo->nHeaderBytes >= 6000 &&
              poOpenInfo->TryToIngest(1000 * 1000) &&
              !IsGeoJSONLikeObject(
                  reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
                  bMightBeSequence, bReadMoreBytes, poOpenInfo, "GeoJSON")))
        {
            return false;
        }
    }

    return !(bMightBeSequence && IsLikelyNewlineSequenceGeoJSON(
                                     poOpenInfo->fpL, poOpenInfo->pabyHeader,
                                     nullptr) == GDAL_IDENTIFY_TRUE);
}

/************************************************************************/
/*                           GeoJSONIsObject()                          */
/************************************************************************/

bool GeoJSONIsObject(const char *pszText, GDALOpenInfo *poOpenInfo)
{
    bool bMightBeSequence = false;
    bool bReadMoreBytes = false;
    if (!IsGeoJSONLikeObject(pszText, bMightBeSequence, bReadMoreBytes,
                             poOpenInfo, "GeoJSON"))
    {
        return false;
    }

    return !(bMightBeSequence &&
             IsLikelyNewlineSequenceGeoJSON(nullptr, nullptr, pszText) ==
                 GDAL_IDENTIFY_TRUE);
}

/************************************************************************/
/*                        GeoJSONSeqFileIsObject()                      */
/************************************************************************/

static bool GeoJSONSeqFileIsObject(GDALOpenInfo *poOpenInfo)
{
    // By default read first 6000 bytes.
    // 6000 was chosen as enough bytes to
    // enable all current tests to pass.

    if (poOpenInfo->fpL == nullptr || !poOpenInfo->TryToIngest(6000))
    {
        return false;
    }

    const char *pszText =
        reinterpret_cast<const char *>(poOpenInfo->pabyHeader);
    if (pszText[0] == '\x1e')
        return IsGeoJSONLikeObject(pszText + 1, poOpenInfo, "GeoJSONSeq");

    bool bMightBeSequence = false;
    bool bReadMoreBytes = false;
    if (!IsGeoJSONLikeObject(pszText, bMightBeSequence, bReadMoreBytes,
                             poOpenInfo, "GeoJSONSeq"))
    {
        if (!(bReadMoreBytes && poOpenInfo->nHeaderBytes >= 6000 &&
              poOpenInfo->TryToIngest(1000 * 1000) &&
              IsGeoJSONLikeObject(
                  reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
                  bMightBeSequence, bReadMoreBytes, poOpenInfo, "GeoJSONSeq")))
        {
            return false;
        }
    }

    if (poOpenInfo->IsSingleAllowedDriver("GeoJSONSeq") &&
        IsLikelyNewlineSequenceGeoJSON(poOpenInfo->fpL, poOpenInfo->pabyHeader,
                                       nullptr) != GDAL_IDENTIFY_FALSE &&
        GDALGetDriverByName("GeoJSONSeq"))
    {
        return true;
    }

    return bMightBeSequence && IsLikelyNewlineSequenceGeoJSON(
                                   poOpenInfo->fpL, poOpenInfo->pabyHeader,
                                   nullptr) == GDAL_IDENTIFY_TRUE;
}

bool GeoJSONSeqIsObject(const char *pszText, GDALOpenInfo *poOpenInfo)
{
    if (pszText[0] == '\x1e')
        return IsGeoJSONLikeObject(pszText + 1, poOpenInfo, "GeoJSONSeq");

    bool bMightBeSequence = false;
    bool bReadMoreBytes = false;
    if (!IsGeoJSONLikeObject(pszText, bMightBeSequence, bReadMoreBytes,
                             poOpenInfo, "GeoJSONSeq"))
    {
        return false;
    }

    if (poOpenInfo->IsSingleAllowedDriver("GeoJSONSeq") &&
        IsLikelyNewlineSequenceGeoJSON(nullptr, nullptr, pszText) !=
            GDAL_IDENTIFY_FALSE &&
        GDALGetDriverByName("GeoJSONSeq"))
    {
        return true;
    }

    return bMightBeSequence &&
           IsLikelyNewlineSequenceGeoJSON(nullptr, nullptr, pszText) ==
               GDAL_IDENTIFY_TRUE;
}

/************************************************************************/
/*                        JSONFGFileIsObject()                          */
/************************************************************************/

static bool JSONFGFileIsObject(GDALOpenInfo *poOpenInfo)
{
    // 6000 somewhat arbitrary. Based on other JSON-like drivers
    if (poOpenInfo->fpL == nullptr || !poOpenInfo->TryToIngest(6000))
    {
        return false;
    }

    const char *pszText =
        reinterpret_cast<const char *>(poOpenInfo->pabyHeader);
    return JSONFGIsObject(pszText, poOpenInfo);
}

bool JSONFGIsObject(const char *pszText, GDALOpenInfo *poOpenInfo)
{
    if (!IsJSONObject(pszText))
        return false;

    if (poOpenInfo->IsSingleAllowedDriver("JSONFG") &&
        GDALGetDriverByName("JSONFG"))
    {
        return true;
    }

    const std::string osWithoutSpace = GetCompactJSon(pszText, strlen(pszText));

    // In theory, conformsTo should be required, but let be lax...
    {
        const auto nPos = osWithoutSpace.find("\"conformsTo\":[");
        if (nPos != std::string::npos)
        {
            for (const char *pszVersion : {"0.1", "0.2", "0.3"})
            {
                if (osWithoutSpace.find(
                        CPLSPrintf("\"[ogc-json-fg-1-%s:core]\"", pszVersion),
                        nPos) != std::string::npos ||
                    osWithoutSpace.find(
                        CPLSPrintf(
                            "\"http://www.opengis.net/spec/json-fg-1/%s\"",
                            pszVersion),
                        nPos) != std::string::npos)
                {
                    return true;
                }
            }
        }
    }

    if (osWithoutSpace.find("\"place\":{\"type\":") != std::string::npos ||
        osWithoutSpace.find("\"place\":{\"coordinates\":") !=
            std::string::npos ||
        osWithoutSpace.find("\"time\":{\"date\":") != std::string::npos ||
        osWithoutSpace.find("\"time\":{\"timestamp\":") != std::string::npos ||
        osWithoutSpace.find("\"time\":{\"interval\":") != std::string::npos)
    {
        return true;
    }

    if (osWithoutSpace.find("\"coordRefSys\":") != std::string::npos ||
        osWithoutSpace.find("\"featureType\":") != std::string::npos)
    {
        // Check that coordRefSys and/or featureType are either at the
        // FeatureCollection or Feature level
        struct MyParser : public CPLJSonStreamingParser
        {
            bool m_bFoundJSONFGFeatureType = false;
            bool m_bFoundJSONFGCoordrefSys = false;
            std::string m_osLevel{};

            void StartObjectMember(const char *pszKey, size_t nLength) override
            {
                if (nLength == strlen("featureType") &&
                    strcmp(pszKey, "featureType") == 0)
                {
                    m_bFoundJSONFGFeatureType =
                        (m_osLevel == "{" ||   // At FeatureCollection level
                         m_osLevel == "{[{");  // At Feature level
                    if (m_bFoundJSONFGFeatureType)
                        StopParsing();
                }
                else if (nLength == strlen("coordRefSys") &&
                         strcmp(pszKey, "coordRefSys") == 0)
                {
                    m_bFoundJSONFGCoordrefSys =
                        (m_osLevel == "{" ||   // At FeatureCollection level
                         m_osLevel == "{[{");  // At Feature level
                    if (m_bFoundJSONFGCoordrefSys)
                        StopParsing();
                }
            }

            void StartObject() override
            {
                m_osLevel += '{';
            }

            void EndObject() override
            {
                if (!m_osLevel.empty())
                    m_osLevel.pop_back();
            }

            void StartArray() override
            {
                m_osLevel += '[';
            }

            void EndArray() override
            {
                if (!m_osLevel.empty())
                    m_osLevel.pop_back();
            }
        };

        MyParser oParser;
        oParser.Parse(pszText, strlen(pszText), true);
        if (oParser.m_bFoundJSONFGFeatureType ||
            oParser.m_bFoundJSONFGCoordrefSys)
        {
            return true;
        }
    }

    return false;
}

/************************************************************************/
/*                           IsLikelyESRIJSONURL()                      */
/************************************************************************/

static bool IsLikelyESRIJSONURL(const char *pszURL)
{
    // URLs with f=json are strong candidates for ESRI JSON services
    // except if they have "/items?", in which case they are likely OAPIF
    return (strstr(pszURL, "f=json") != nullptr ||
            strstr(pszURL, "f=pjson") != nullptr ||
            strstr(pszURL, "resultRecordCount=") != nullptr) &&
           strstr(pszURL, "/items?") == nullptr;
}

/************************************************************************/
/*                           GeoJSONGetSourceType()                     */
/************************************************************************/

GeoJSONSourceType GeoJSONGetSourceType(GDALOpenInfo *poOpenInfo)
{
    GeoJSONSourceType srcType = eGeoJSONSourceUnknown;

    // NOTE: Sometimes URL ends with .geojson token, for example
    //       http://example/path/2232.geojson
    //       It's important to test beginning of source first.
    if (STARTS_WITH_CI(poOpenInfo->pszFilename, "GEOJSON:http://") ||
        STARTS_WITH_CI(poOpenInfo->pszFilename, "GEOJSON:https://") ||
        STARTS_WITH_CI(poOpenInfo->pszFilename, "GEOJSON:ftp://"))
    {
        srcType = eGeoJSONSourceService;
    }
    else if (STARTS_WITH_CI(poOpenInfo->pszFilename, "http://") ||
             STARTS_WITH_CI(poOpenInfo->pszFilename, "https://") ||
             STARTS_WITH_CI(poOpenInfo->pszFilename, "ftp://"))
    {
        if (poOpenInfo->IsSingleAllowedDriver("GeoJSON"))
        {
            return eGeoJSONSourceService;
        }
        if ((strstr(poOpenInfo->pszFilename, "SERVICE=WFS") ||
             strstr(poOpenInfo->pszFilename, "service=WFS") ||
             strstr(poOpenInfo->pszFilename, "service=wfs")) &&
            !strstr(poOpenInfo->pszFilename, "json"))
        {
            return eGeoJSONSourceUnknown;
        }
        if (IsLikelyESRIJSONURL(poOpenInfo->pszFilename))
        {
            return eGeoJSONSourceUnknown;
        }
        srcType = eGeoJSONSourceService;
    }
    else if (STARTS_WITH_CI(poOpenInfo->pszFilename, "GeoJSON:"))
    {
        VSIStatBufL sStat;
        if (VSIStatL(poOpenInfo->pszFilename + strlen("GeoJSON:"), &sStat) == 0)
        {
            return eGeoJSONSourceFile;
        }
        const char *pszText = poOpenInfo->pszFilename + strlen("GeoJSON:");
        if (GeoJSONIsObject(pszText, poOpenInfo))
            return eGeoJSONSourceText;
        return eGeoJSONSourceUnknown;
    }
    else if (GeoJSONIsObject(poOpenInfo->pszFilename, poOpenInfo))
    {
        srcType = eGeoJSONSourceText;
    }
    else if (GeoJSONFileIsObject(poOpenInfo))
    {
        srcType = eGeoJSONSourceFile;
    }

    return srcType;
}

/************************************************************************/
/*                     ESRIJSONDriverGetSourceType()                    */
/************************************************************************/

GeoJSONSourceType ESRIJSONDriverGetSourceType(GDALOpenInfo *poOpenInfo)
{
    if (STARTS_WITH_CI(poOpenInfo->pszFilename, "ESRIJSON:http://") ||
        STARTS_WITH_CI(poOpenInfo->pszFilename, "ESRIJSON:https://") ||
        STARTS_WITH_CI(poOpenInfo->pszFilename, "ESRIJSON:ftp://"))
    {
        return eGeoJSONSourceService;
    }
    else if (STARTS_WITH(poOpenInfo->pszFilename, "http://") ||
             STARTS_WITH(poOpenInfo->pszFilename, "https://") ||
             STARTS_WITH(poOpenInfo->pszFilename, "ftp://"))
    {
        if (poOpenInfo->IsSingleAllowedDriver("ESRIJSON"))
        {
            return eGeoJSONSourceService;
        }
        if (IsLikelyESRIJSONURL(poOpenInfo->pszFilename))
        {
            return eGeoJSONSourceService;
        }
        return eGeoJSONSourceUnknown;
    }

    if (STARTS_WITH_CI(poOpenInfo->pszFilename, "ESRIJSON:"))
    {
        VSIStatBufL sStat;
        if (VSIStatL(poOpenInfo->pszFilename + strlen("ESRIJSON:"), &sStat) ==
            0)
        {
            return eGeoJSONSourceFile;
        }
        const char *pszText = poOpenInfo->pszFilename + strlen("ESRIJSON:");
        if (ESRIJSONIsObject(pszText, poOpenInfo))
            return eGeoJSONSourceText;
        return eGeoJSONSourceUnknown;
    }

    if (poOpenInfo->fpL == nullptr)
    {
        const char *pszText = poOpenInfo->pszFilename;
        if (ESRIJSONIsObject(pszText, poOpenInfo))
            return eGeoJSONSourceText;
        return eGeoJSONSourceUnknown;
    }

    // By default read first 6000 bytes.
    // 6000 was chosen as enough bytes to
    // enable all current tests to pass.
    if (!poOpenInfo->TryToIngest(6000))
    {
        return eGeoJSONSourceUnknown;
    }

    if (poOpenInfo->pabyHeader != nullptr &&
        ESRIJSONIsObject(reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
                         poOpenInfo))
    {
        return eGeoJSONSourceFile;
    }
    return eGeoJSONSourceUnknown;
}

/************************************************************************/
/*                     TopoJSONDriverGetSourceType()                    */
/************************************************************************/

GeoJSONSourceType TopoJSONDriverGetSourceType(GDALOpenInfo *poOpenInfo)
{
    if (STARTS_WITH_CI(poOpenInfo->pszFilename, "TopoJSON:http://") ||
        STARTS_WITH_CI(poOpenInfo->pszFilename, "TopoJSON:https://") ||
        STARTS_WITH_CI(poOpenInfo->pszFilename, "TopoJSON:ftp://"))
    {
        return eGeoJSONSourceService;
    }
    else if (STARTS_WITH(poOpenInfo->pszFilename, "http://") ||
             STARTS_WITH(poOpenInfo->pszFilename, "https://") ||
             STARTS_WITH(poOpenInfo->pszFilename, "ftp://"))
    {
        if (poOpenInfo->IsSingleAllowedDriver("TOPOJSON"))
        {
            return eGeoJSONSourceService;
        }
        if (IsLikelyESRIJSONURL(poOpenInfo->pszFilename))
        {
            return eGeoJSONSourceUnknown;
        }
        return eGeoJSONSourceService;
    }

    if (STARTS_WITH_CI(poOpenInfo->pszFilename, "TopoJSON:"))
    {
        VSIStatBufL sStat;
        if (VSIStatL(poOpenInfo->pszFilename + strlen("TopoJSON:"), &sStat) ==
            0)
        {
            return eGeoJSONSourceFile;
        }
        const char *pszText = poOpenInfo->pszFilename + strlen("TopoJSON:");
        if (TopoJSONIsObject(pszText, poOpenInfo))
            return eGeoJSONSourceText;
        return eGeoJSONSourceUnknown;
    }

    if (poOpenInfo->fpL == nullptr)
    {
        const char *pszText = poOpenInfo->pszFilename;
        if (TopoJSONIsObject(pszText, poOpenInfo))
            return eGeoJSONSourceText;
        return eGeoJSONSourceUnknown;
    }

    // By default read first 6000 bytes.
    // 6000 was chosen as enough bytes to
    // enable all current tests to pass.
    if (!poOpenInfo->TryToIngest(6000))
    {
        return eGeoJSONSourceUnknown;
    }

    if (poOpenInfo->pabyHeader != nullptr &&
        TopoJSONIsObject(reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
                         poOpenInfo))
    {
        return eGeoJSONSourceFile;
    }
    return eGeoJSONSourceUnknown;
}

/************************************************************************/
/*                          GeoJSONSeqGetSourceType()                   */
/************************************************************************/

GeoJSONSourceType GeoJSONSeqGetSourceType(GDALOpenInfo *poOpenInfo)
{
    GeoJSONSourceType srcType = eGeoJSONSourceUnknown;

    if (STARTS_WITH_CI(poOpenInfo->pszFilename, "GEOJSONSeq:http://") ||
        STARTS_WITH_CI(poOpenInfo->pszFilename, "GEOJSONSeq:https://") ||
        STARTS_WITH_CI(poOpenInfo->pszFilename, "GEOJSONSeq:ftp://"))
    {
        srcType = eGeoJSONSourceService;
    }
    else if (STARTS_WITH_CI(poOpenInfo->pszFilename, "http://") ||
             STARTS_WITH_CI(poOpenInfo->pszFilename, "https://") ||
             STARTS_WITH_CI(poOpenInfo->pszFilename, "ftp://"))
    {
        if (poOpenInfo->IsSingleAllowedDriver("GeoJSONSeq"))
        {
            return eGeoJSONSourceService;
        }
        if (IsLikelyESRIJSONURL(poOpenInfo->pszFilename))
        {
            return eGeoJSONSourceUnknown;
        }
        srcType = eGeoJSONSourceService;
    }
    else if (STARTS_WITH_CI(poOpenInfo->pszFilename, "GEOJSONSeq:"))
    {
        VSIStatBufL sStat;
        if (VSIStatL(poOpenInfo->pszFilename + strlen("GEOJSONSeq:"), &sStat) ==
            0)
        {
            return eGeoJSONSourceFile;
        }
        const char *pszText = poOpenInfo->pszFilename + strlen("GEOJSONSeq:");
        if (GeoJSONSeqIsObject(pszText, poOpenInfo))
            return eGeoJSONSourceText;
        return eGeoJSONSourceUnknown;
    }
    else if (GeoJSONSeqIsObject(poOpenInfo->pszFilename, poOpenInfo))
    {
        srcType = eGeoJSONSourceText;
    }
    else if (GeoJSONSeqFileIsObject(poOpenInfo))
    {
        srcType = eGeoJSONSourceFile;
    }

    return srcType;
}

/************************************************************************/
/*                      JSONFGDriverGetSourceType()                     */
/************************************************************************/

GeoJSONSourceType JSONFGDriverGetSourceType(GDALOpenInfo *poOpenInfo)
{
    GeoJSONSourceType srcType = eGeoJSONSourceUnknown;

    if (STARTS_WITH_CI(poOpenInfo->pszFilename, "JSONFG:http://") ||
        STARTS_WITH_CI(poOpenInfo->pszFilename, "JSONFG:https://") ||
        STARTS_WITH_CI(poOpenInfo->pszFilename, "JSONFG:ftp://"))
    {
        srcType = eGeoJSONSourceService;
    }
    else if (STARTS_WITH_CI(poOpenInfo->pszFilename, "http://") ||
             STARTS_WITH_CI(poOpenInfo->pszFilename, "https://") ||
             STARTS_WITH_CI(poOpenInfo->pszFilename, "ftp://"))
    {
        if (poOpenInfo->IsSingleAllowedDriver("JSONFG"))
        {
            return eGeoJSONSourceService;
        }
        if (IsLikelyESRIJSONURL(poOpenInfo->pszFilename))
        {
            return eGeoJSONSourceUnknown;
        }
        srcType = eGeoJSONSourceService;
    }
    else if (STARTS_WITH_CI(poOpenInfo->pszFilename, "JSONFG:"))
    {
        VSIStatBufL sStat;
        const size_t nJSONFGPrefixLen = strlen("JSONFG:");
        if (VSIStatL(poOpenInfo->pszFilename + nJSONFGPrefixLen, &sStat) == 0)
        {
            return eGeoJSONSourceFile;
        }
        const char *pszText = poOpenInfo->pszFilename + nJSONFGPrefixLen;
        if (JSONFGIsObject(pszText, poOpenInfo))
            return eGeoJSONSourceText;
        return eGeoJSONSourceUnknown;
    }
    else if (JSONFGIsObject(poOpenInfo->pszFilename, poOpenInfo))
    {
        srcType = eGeoJSONSourceText;
    }
    else if (JSONFGFileIsObject(poOpenInfo))
    {
        srcType = eGeoJSONSourceFile;
    }

    return srcType;
}

/************************************************************************/
/*                        GeoJSONStringPropertyToFieldType()            */
/************************************************************************/

OGRFieldType GeoJSONStringPropertyToFieldType(json_object *poObject,
                                              int &nTZFlag)
{
    if (poObject == nullptr)
    {
        return OFTString;
    }
    const char *pszStr = json_object_get_string(poObject);

    nTZFlag = 0;
    OGRField sWrkField;
    CPLPushErrorHandler(CPLQuietErrorHandler);
    const bool bSuccess = CPL_TO_BOOL(OGRParseDate(pszStr, &sWrkField, 0));
    CPLPopErrorHandler();
    CPLErrorReset();
    if (bSuccess)
    {
        const bool bHasDate =
            strchr(pszStr, '/') != nullptr || strchr(pszStr, '-') != nullptr;
        const bool bHasTime = strchr(pszStr, ':') != nullptr;
        nTZFlag = sWrkField.Date.TZFlag;
        if (bHasDate && bHasTime)
            return OFTDateTime;
        else if (bHasDate)
            return OFTDate;
        else
            return OFTTime;
        // TODO: What if both are false?
    }
    return OFTString;
}

/************************************************************************/
/*                   GeoJSONHTTPFetchWithContentTypeHeader()            */
/************************************************************************/

CPLHTTPResult *GeoJSONHTTPFetchWithContentTypeHeader(const char *pszURL)
{
    std::string osHeaders;
    const char *pszGDAL_HTTP_HEADERS =
        CPLGetConfigOption("GDAL_HTTP_HEADERS", nullptr);
    bool bFoundAcceptHeader = false;
    if (pszGDAL_HTTP_HEADERS)
    {
        bool bHeadersDone = false;
        // Compatibility hack for "HEADERS=Accept: text/plain, application/json"
        if (strstr(pszGDAL_HTTP_HEADERS, "\r\n") == nullptr)
        {
            const char *pszComma = strchr(pszGDAL_HTTP_HEADERS, ',');
            if (pszComma != nullptr && strchr(pszComma, ':') == nullptr)
            {
                osHeaders = pszGDAL_HTTP_HEADERS;
                bFoundAcceptHeader =
                    STARTS_WITH_CI(pszGDAL_HTTP_HEADERS, "Accept:");
                bHeadersDone = true;
            }
        }
        if (!bHeadersDone)
        {
            // We accept both raw headers with \r\n as a separator, or as
            // a comma separated list of foo: bar values.
            const CPLStringList aosTokens(
                strstr(pszGDAL_HTTP_HEADERS, "\r\n")
                    ? CSLTokenizeString2(pszGDAL_HTTP_HEADERS, "\r\n", 0)
                    : CSLTokenizeString2(pszGDAL_HTTP_HEADERS, ",",
                                         CSLT_HONOURSTRINGS));
            for (int i = 0; i < aosTokens.size(); ++i)
            {
                if (!osHeaders.empty())
                    osHeaders += "\r\n";
                if (!bFoundAcceptHeader)
                    bFoundAcceptHeader =
                        STARTS_WITH_CI(aosTokens[i], "Accept:");
                osHeaders += aosTokens[i];
            }
        }
    }
    if (!bFoundAcceptHeader)
    {
        if (!osHeaders.empty())
            osHeaders += "\r\n";
        osHeaders += "Accept: text/plain, application/json";
    }

    CPLStringList aosOptions;
    aosOptions.SetNameValue("HEADERS", osHeaders.c_str());
    CPLHTTPResult *pResult = CPLHTTPFetch(pszURL, aosOptions.List());

    if (nullptr == pResult || 0 == pResult->nDataLen ||
        0 != CPLGetLastErrorNo())
    {
        CPLHTTPDestroyResult(pResult);
        return nullptr;
    }

    if (0 != pResult->nStatus)
    {
        CPLError(CE_Failure, CPLE_AppDefined, "Curl reports error: %d: %s",
                 pResult->nStatus, pResult->pszErrBuf);
        CPLHTTPDestroyResult(pResult);
        return nullptr;
    }

    return pResult;
}