4
$\begingroup$

I want to export a list of url's as a JSON file.

For instance:

Export[NotebookDirectory[] <> "file.json", {"https://www.google.com/", "https://www.google.com/"}, "JSON"] 

Unfortunately mathematica adds back slashes to the file.

[
"https:\/\/www.google.com\/",
"https:\/\/www.google.com\/"
]

Question:

how to export a list of url's to a JSON file?

$\endgroup$
3
  • 1
    $\begingroup$ It seems that escaping / characters is allowed in JSON but not mandatory. So the result is valid JSON and I think every JSON interpreter should read this back as the original strings (that is without the backslashes). You can for example check that Mathematicas Export does this. Can you explain why you don't want those slashes to be escaped? $\endgroup$ Commented Apr 18, 2021 at 23:19
  • $\begingroup$ @AlbertRetey your right! I didn't realise that escaping characters was allowed. Thanks $\endgroup$ Commented Apr 19, 2021 at 4:55
  • $\begingroup$ you are welcome, I have added another answer with some more details for reference. $\endgroup$ Commented Apr 20, 2021 at 6:33

2 Answers 2

2
$\begingroup$

If I understand the (more or less) official standard description correctly, a / is allowed to be escaped with \ as Export does, but does not have to be escaped. Thus the JSON that Export generates is valid and should be read back as the original string (without the escape character) by any correctly implemented JSON import code.

So if you are just longing for valid JSON, then there is nothing to do. If for any reason you want to get rid of the escape characters, that can be done like in your own answer and the result will still be valid JSON.

$\endgroup$
3
$\begingroup$

adapting @Kuba's solution to a similar question.

jsonExport[file_, listOfURLs_]:=FileTemplateApply[#, #2[[1]], file] & @@ Reap@ExportString[URL /@ listOfURLs, "RawJSON", "ConversionFunction" -> Function[Sow[First@#]; "``"]]

.

jsonExport[NotebookDirectory[] <> "file.json", {"https://www.google.com/", "https://www.google.com/"}] // Import
{"https://www.google.com/", "https://www.google.com/"}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.