ValueError: syntax error in JSON

All ESP8266 boards running MicroPython.
Official boards are the Adafruit Huzzah and Feather boards.
Target audience: MicroPython users with an ESP8266 board.
Post Reply
microBoa
Posts: 13
Joined: Mon Apr 05, 2021 6:09 am

ValueError: syntax error in JSON

Post by microBoa » Sat Apr 10, 2021 10:54 pm

I'm trying to read/write a dict{} containing settings. I've read the docs, but I'm getting ValueError: syntax error in JSON when I try to read the settings. I'm not sure how to confirm they were written correctly. What am I missing? (sorry don't know why formatting is off, using CODE tags). There's some magic in between get/save to update the values saved in the dict{}.

Code: Select all

import ujson
import uos
import machine

class settings():
  value={
    'aaa'  : "1",
    'bbb'  : "2",
    'ccc'   : "3",
    'ddd'  : "4",
    'eee'  : "5",
    'fff'    : "6",
    'ggg'  : "7",
    'hhh'  : "8",
    'iii'     : "9"
  }
  
def get_cfg():
  if 'config.json' in uos.listdir():
    with open('config.json', 'rb') as f:
      conf = ujson.load(f)

def save():
  if 'config.json' in uos.listdir():
    uos.rename('config.json', 'config.bak')

  with open('config.json', 'wb') as f:
    ujson.dump(conf, f)
  
conf = settings()  
save()
get_cfg()
  
I get this error:

Code: Select all

  File "main.py", line 38, in get_cfg
ValueError: syntax error in JSON

scruss
Posts: 68
Joined: Sat Aug 12, 2017 2:27 pm

Re: ValueError: syntax error in JSON

Post by scruss » Sun Apr 11, 2021 2:42 am

When I try that on MicroPython on Linux, config.json ends up containing:

Code: Select all

<settings object at 7faf2a7c5200>
Can you save classes in ujson objects?

microBoa
Posts: 13
Joined: Mon Apr 05, 2021 6:09 am

Re: ValueError: syntax error in JSON

Post by microBoa » Sun Apr 11, 2021 6:15 am

Thanks, you're right. I needed to add the dict name:

conf.value

Code: Select all

ujson.dump(conf.value, f)
Thanks for taking a look and spotting that!

Post Reply