5
$\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$
7
  • $\begingroup$ So // StringReplace["\\/" -> "/"] is not an option? $\endgroup$
    – Kuba
    Commented Feb 4, 2019 at 21:41
  • 1
    $\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.
    Commented Feb 4, 2019 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.
    Commented Feb 4, 2019 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
    Commented Feb 4, 2019 at 23:01
  • 2
    $\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$ Commented Feb 5, 2019 at 0:45

1 Answer 1

4
$\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 and acknowledge you have read our privacy policy.

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