fromJSON throws `the string "..." is not allowed to refer to a store path`

nix-repl> f = x: builtins.fromJSON (builtins.toJSON x)

nix-repl> f ./.
error: the string '"/nix/store/n8qjpszps5qjnikc86f2fmcxdw8lwmhd-playground"' is not allowed to refer to a store path (such as '/nix/store/n8qjpszps5qjnikc86f2fmcxdw8lwmhd-playground')

       at «string»:1:5:

            1|  x: builtins.fromJSON (builtins.toJSON x)
             |     ^

nix-repl> f (toString ./.) # this works
"/home/figsoda/playground"

nix-repl> f (toString (builtins.path { path = ./.; })) # but this doesn't
error: the string '"/nix/store/n8qjpszps5qjnikc86f2fmcxdw8lwmhd-playground"' is not allowed to refer to a store path (such as '/nix/store/n8qjpszps5qjnikc86f2fmcxdw8lwmhd-playground')

       at «string»:1:5:

            1|  x: builtins.fromJSON (builtins.toJSON x)
             |     ^

This is not an issue with toJSON, since the error can be reproduced without it

nix-repl> builtins.fromJSON "${./.}" # I know this isn't valid JSON, but it should run into a parsing error instead
error: the string '/nix/store/gbk2icvy3drcbyyswsrh20dqiagbcmxl-playground' is not allowed to refer to a store path (such as '/nix/store/gbk2icvy3drcbyyswsrh20dqiagbcmxl-playground')

       at «string»:1:1:

            1| builtins.fromJSON "${./.}"
             | ^

nix-repl> builtins.fromJSON (toString ./.) # this is what I expected to happen
error: [json.exception.parse_error.101] parse error at line 1, column 1: syntax error while parsing value - invalid literal; last read: '/'

nix-repl> import "${./.}" # import works, for some reason
42
nix-repl> builtins.fromJSON "${builtins.unsafeDiscardStringContext ./.}"
error: [json.exception.parse_error.101] parse error at line 1, column 1: syntax error while parsing value - invalid literal; last read: '/'
1 Like

it does work, but why do I need an unsafe function to use builtins.fromJSON with a path?

I guess that it is because you have no guarantees about that realized derivation exists out of your system. Is off the DAG.