4
$\begingroup$

If you JSON export an association with a url, it will espace the forward slashes like this:

ExportString[ <|"url" -> "http://s2d3.scene1.com/medium/94760712386071_001.jpg"|>, 
"JSON"]

enter image description here

How can I get this not to happen?

$\endgroup$
  • $\begingroup$ So // StringReplace["\\/" -> "/"] is not an option? $\endgroup$ – Kuba Feb 4 at 21:41
  • $\begingroup$ In practice, it would be during a call to Export not ExportString and only a few of the fields are URLs (don't want to un-escape all of them). $\endgroup$ – M.R. Feb 4 at 22:40
  • $\begingroup$ @kuba Are you saying do this: Export["~/Downloads/tmp.json", ExportString[<|"a" -> "http://a.b/c:de", "b" -> 123, "c" -> <|"url" -> "http://s2d3.scene1.com/medium/94760712386071_001.jpg"|>|>, "JSON"] // StringReplace["\\/" -> "/"], "Text"] $\endgroup$ – M.R. Feb 4 at 22:59
  • 1
    $\begingroup$ I think you need to export as "String" not "Text" to not double encode. It may not matter here but unless I am mistaken, it should be "String". $\endgroup$ – Kuba Feb 4 at 23:01
  • 1
    $\begingroup$ There's no way to do this from JSON Export directly (even in any undocumented way), some kind of StringReplace on ExportString and Exporting as "String" like @Kuba has recommended would be the best solution most likely. $\endgroup$ – GenericAccountName Feb 5 at 0:45
2
$\begingroup$

Don't know if there is a neat solution but here is one approach. Assuming you can mark your urls with URL:

json = <|"url" -> URL @ "http://s2d3.scene1.com/medium/94760712386071_001.jpg"
  , "urlω2" -> URL@"http://wolfram.com"
  |>;

FileTemplateApply[#, #2[[1]], "file.json"] & @@ 
Reap @ 
ExportString[
  json
, "RawJSON"
,  "ConversionFunction" -> Function[Sow[First@#]; "``"]
]


FilePrint@"file.json"
Import["file.json", "RawJSON"]

{ "url":"http://s2d3.scene1.com/medium/94760712386071_001.jpg", "urlÏ2":"http://wolfram.com" }

<|"url" -> "http://s2d3.scene1.com/medium/94760712386071_001.jpg",  
    "urlω2" -> "http://wolfram.com"|>
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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