Just starting out? Need help? Post your questions and find answers here.
falsam
 
Posts: 253
Joined: Mon May 05, 2014 9:49 pm
Location: France

Save JSON in local storage

by falsam Wed Oct 11, 2017 2:40 pm

I'm trying to create a backup (JSON format) of a chained list in the browser's local storage.

When I start the code, the registration of a single element works. If I run the code a second time, I have a console error when saving in JSON format.
console wrote:Uncaught TypeError: Cannot convert undefined or null to object
at Function.keys (<anonymous>)
at spider_JSON_DumpStructure (spiderbasic.js:284)
at spider_JSON_DumpField (spiderbasic.js:283)
at spider_InsertJSONList (spiderbasic.js:284)
at f_savedata (spiderbasic.js:306)
My code
Code: Select all
EnableExplicit

Declare Start()
Declare InsertData()
Declare ShowResult()
Declare LoadData()
Declare SaveData()

Structure NewRecord
  name.s
  phone.s
EndStructure
Global NewList Contacts.NewRecord()

Start()

Procedure Start()
  LoadData()
  InsertData()
  ShowResult()
  SaveData()
EndProcedure

Procedure InsertData()
  Protected n = ListSize(Contacts())
  AddElement(Contacts())
  With Contacts()
    \name = "Name " + Str(n)
    \phone= LSet(Str(n), 6 , Str(n))
  EndWith
EndProcedure

Procedure ShowResult()
  ForEach Contacts()
    With Contacts()
      Debug \name + " - " + \phone
    EndWith
  Next
EndProcedure

Procedure LoadData()
  Protected Buffer.s = ""
 
  !v_buffer = localStorage.getItem('myStorage');
  !if (v_buffer === null) { v_buffer = "" }
 
  If Len(Buffer) <> 0
    If ParseJSON(0, Buffer) 
      Debug "Load " + Buffer
      If Buffer <> #Null$
        ExtractJSONList(JSONValue(0), Contacts())
      EndIf
    EndIf
  Else
    Debug "no data in local storage"
  EndIf
EndProcedure

Procedure SaveData()
  Protected Buffer.s
 
  If CreateJSON(0)
    InsertJSONList(JSONValue(0), Contacts()) ;<- Console : Cannot convert undefined or null to object
    Buffer = ComposeJSON(0)
    !localStorage.setItem('myStorage', v_buffer);
  EndIf
EndProcedure 
Execute this code twice.

Thank you in advance for your suggestions. ;)
➽ Windows 10 - JDK 1.8 - SB 2.20 - Android 5.5
Mood
http://falsam.com

Sorry for my poor english
Return to Coding Questions

Who is online

Users browsing this forum: No registered users and 1 guest