0

I am using blender on windows, following the tutorial: Visualize JSON Data in blender but I am stuck trying to open the JSON file.

My code (windows):

    import json 

    with open('C:\Users\Franktabs\Documents\export.json') as f:
        j = json.load(f)
        print(j)

His code(linux):

import json

with open('/home/chris/Downalds/tutorial.son') as f:
    j = json.load(f)
    print(j)

Error Message:

Python:   File "C:\Users\Franktabs\Documents\Json2.blend\My Script", line 3
     with open('C:\Users\Franktabs\Documents\export.json') as f:
                   ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
 location: <unknown location>:-1

Solutions Tried:

  • Using import bpy
  • Using double \
  • Using 'r'
  • Using utf-8
  • Checking the file type is actually .json
  • Checking the route and name of the file in properties

Solutions sources from a person with the same problem: post1,post2

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 1
    Does this answer your question? [using backslash in python (not to escape)](https://stackoverflow.com/questions/3380484/using-backslash-in-python-not-to-escape) – Woodford Sep 07 '21 at 16:20
  • 1
    Backslashes inside a string (such as your Windows path) have a special meaning and must be *escaped* to be used literally. See the answers to the question linked above for details/workarounds. – Woodford Sep 07 '21 at 16:22
  • Change your backward slashes ``\`` to forward slashes `/`. – MattDMo Sep 07 '21 at 16:25
  • @MattDMo Why? `os.path.join` should be used instead. – OneCricketeer Sep 07 '21 at 16:33
  • @OneCricketeer `os.path.join` is still going to need a base path, which will almost certainly include `\U...`, which is what is triggering the unicode error. Forward slashes are perfectly acceptable in Windows path literals, and OP claimed to have tried ``\\`` and `r` literals (which I doubt were done correctly, as they failed, but that's another topic). It's just something else to try without changing the actual code. – MattDMo Sep 07 '21 at 16:45
  • @MattDMo `pathlib.Path.home()` should return the Users directory, though – OneCricketeer Sep 07 '21 at 16:48
  • @OneCricketeer I agree, there are lots of things that *could* be done to make this problem go away, I just chose the simplest one. – MattDMo Sep 07 '21 at 16:54

1 Answers1

2

As mentioned \U is a unicode escape character, and is likely part of the issue. Without seeing the \\ usage or r'' code or error, hard to know what the issues there could be...

This should work for an OS-agnostic solution, assuming you have a Documents directory where the file exists

import json
import pathlib

with open(pathlib.Path.home() / 'Documents' / 'export.json') as f:
  data = json.load(f)
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245