ob-http icon indicating copy to clipboard operation
ob-http copied to clipboard

Make the json formatting bearable

Open CestDiego opened this issue 10 years ago • 4 comments

Hello, this project is awesome, thank you for it. I have one suggestion though, can you make it so that we have json formatting by default? or sth like that? to ensure we POST valid data.

CestDiego avatar Apr 15 '15 02:04 CestDiego

Hi, do you mean json syntax highlighting in request body? That should be possible, but I haven't figured out how sophisticated syntax highlighting works yet, currently it's done by regular expression :(

zweifisch avatar Apr 15 '15 12:04 zweifisch

Yes, maybe using sth like polymode? https://github.com/vspinu/polymode could be a first step

CestDiego avatar Apr 26 '15 06:04 CestDiego

I don't think that would be a good enhancement for ob-http since org mode already provides most what you need. I.e. you can get syntax highlighted json by using a standard src block:

#+name: input-json
#+begin_src json
<your json>
#+end_src

The only problem is that you don't want to evaluate this src block but just use its contents. I found no standard way in org mode to do this, so I wrote a small elisp helper function:

(defun extract-src-content (name)
  (save-excursion
    (org-babel-goto-named-src-block name)
    (org-element-property :value (org-element-at-point))))

Then you can do this in your http src block:

#+begin_src http :var input-json=(extract-src-content "input-json")
POST <use 'input-json' variable anywhere you like>
#+end_src

In fact I use this when I need to write longer jq scripts and passing them as a :select parameter. The only problem is that some characters need to be escaped correctly for jq so I use this modified version of extract-src-content:

(defun extract-src-content (name)
  (save-match-data
    (replace-regexp-in-string
     "[\"$]" "\\\\\\&"
     (save-excursion
       (org-babel-goto-named-src-block name)
       (org-element-property :value (org-element-at-point))))))

bitti avatar May 25 '17 19:05 bitti

On second thought, I figured you don't even need my function. Vanilla org mode is enough to achieve what you want. Just use a json example blog:

#+name: input-json
#+begin_example json
<your json>
#+end_example

Then you can use it directly as input

#+begin_src http :var input-json=input-json
POST <some url>
 
${input-json}
#+end_src

That doesn't work for :select parameters though, since it doesn't interpret references. And even if not it would probably still yield escaping problems. It would be nice if this can be fixed though, since that is not how src parameters behave in general. @zweifisch: should I open a ticket for that?

bitti avatar May 25 '17 21:05 bitti