Issue while trying to read a json from a file

Just starting out? Need help? Post your questions and find answers here.
Josepho
Posts: 5
Joined: Mon Sep 13, 2021 9:08 pm

Issue while trying to read a json from a file

Post by Josepho »

Im trying to import a json by using the openfilerequester so the players can opena json with a web program, i have this code but its returning me an error

Unexpected token in JSON at position 0
-1
-1

Anyone knows where is the mistake?

Code: Select all

Debug Input$

Enumeration
  #file_read
  #json_result
EndEnumeration

Structure Location
  x.l
  y.l
EndStructure

Global NewList Locations.Location()

For i = 0 To 10
  AddElement(Locations())
  Locations()\x = Random(100)
  Locations()\y = Random(100)
Next

Procedure fileReadCall(Status, Filename$, File, Size)
  If Status = #PB_Status_Loaded
    Debug "File: " + Filename$ + " - Size: " + Size + " bytes"
    Debug "Reading.."
    Input$ = ReadString(#file_read,#PB_UTF8 | #PB_File_IgnoreEOL)
    Debug Input$
    
    If ParseJSON(#json_result,Input$)
      ClearList(Locations())    
      ExtractJSONList(JSONValue(#json_result),Locations())
      
      ForEach Locations()
        Debug Str(Locations()\x) + ", " + Str(Locations()\y)
      Next
    Else
      Debug "json read error"
      Debug JSONErrorMessage()
      Debug JSONErrorLine()
      Debug JSONErrorPosition()
    EndIf
  EndIf
EndProcedure

Procedure fileImporReaded()
  If NextSelectedFile()
    ReadFile(#file_read, SelectedFileID(), @fileReadCall(), #PB_LocalFile | #PB_UTF8)
  EndIf
EndProcedure

fileson = CreateJSON(#PB_Any)
InsertJSONList(JSONValue(fileson),Locations())
ExportJSON(fileson,"demo.json")

Procedure ChooseFileEvent()
  OpenFileRequester(".json",@fileImporReaded(),#PB_Requester_MultiSelection)
EndProcedure

OpenWindow(0, 0, 0, 300, 50, "Read file example", #PB_Window_ScreenCentered)
ButtonGadget(0, 10, 10, 280, 30, "Choose a text file...")

BindGadgetEvent(0, @ChooseFileEvent())
User avatar
Peter
Posts: 1086
Joined: Mon Feb 24, 2014 10:17 pm
Location: 127.0.0.1:9080
Contact:

Re: Issue while trying to read a json from a file

Post by Peter »

ExportJSON() saves the JSON with a BOM (Byte Order Mark)

Image

Before you execute the ReadString(), you must execute a ReadStringFormat() to skip the BOM.

Code: Select all

    [...]
    Debug "Reading.."
    ReadStringFormat(#file_read) ; <-- skip the BOM (if detected)
    Input$ = ReadString(#file_read,#PB_UTF8 | #PB_File_IgnoreEOL)
    [...]
Josepho
Posts: 5
Joined: Mon Sep 13, 2021 9:08 pm

Re: Issue while trying to read a json from a file

Post by Josepho »

MAny thanks!
Post Reply