|
| 1 | +function response = json2couch(jsonfile, couchdburl, dbname, docname, options) |
| 2 | +% |
| 3 | +% json2couch(jsonfile, servername, dbname, docname, options) |
| 4 | +% |
| 5 | +% uploading JSON-encoded data to a CouchDB database (a NoSQL database) |
| 6 | +% as a document |
| 7 | +% |
| 8 | +% author: Qianqian Fang (q.fang <at> neu.edu) |
| 9 | +% |
| 10 | +% input: |
| 11 | +% jsonfile: the path to the .json file |
| 12 | +% couchdburl: the URL of the CouchDB server, usually it is |
| 13 | +% http://servername:5984 where servername is your own |
| 14 | +% server's domain name |
| 15 | +% dbname: the database for whcih the file is uploaded to, must be |
| 16 | +% created first |
| 17 | +% docname: the document name for the uploaded JSON data |
| 18 | +% options: a options structure created by weboptions(), defining |
| 19 | +% Username, Password, ContentType when such information is |
| 20 | +% desired to access the server; by default, |
| 21 | +% options.ContentType is set to 'json' and |
| 22 | +% options.RequestMethod is set to 'POST' |
| 23 | +% |
| 24 | +% if options is a string, it defines a template for a curl |
| 25 | +% command, for example 'curl -X PUT -d @$f $u/$d/$s'. |
| 26 | +% Variables (start with $) are expanded as |
| 27 | +% $f -> path of the json file (first input) |
| 28 | +% $u -> couchdb full URL (second input) |
| 29 | +% $d -> database name (third input) |
| 30 | +% $s -> document name (forth input) |
| 31 | +% |
| 32 | +% examples: |
| 33 | +% values = inputdlg({'Username:', 'Password:'}); |
| 34 | +% options = weboptions('ContentType', 'json', 'RequestMethod', 'POST', 'Username',values{1},'Password',values{2}); |
| 35 | +% json2couch('ds001.json', 'https://example.com:5984', 'bids-samples', 'ds001', options) |
| 36 | +% json2couch('ds001.json', sprintf('https://%s:%[email protected]:5984', values{1}, values{2}), 'bids-samples', 'ds001', 'curl -X PUT -d @$f $u/$d/$s') |
| 37 | +% |
| 38 | +% license: |
| 39 | +% BSD license, see LICENSE_BSD.txt files for details |
| 40 | +% |
| 41 | +% -- this function is part of JBIDS toolbox (https://neurojson.org/#software) |
| 42 | +% |
| 43 | + |
| 44 | +if (nargin < 5) |
| 45 | + options = weboptions(''); |
| 46 | +end |
| 47 | + |
| 48 | +if (~ischar(options) && ~isa(options, 'string')) |
| 49 | + options.ContentType = 'json'; |
| 50 | + options.RequestMethod = 'POST'; |
| 51 | + response = webwrite([couchdburl '/' dbname '/' docname], fileread(jsonfile), options); |
| 52 | +else |
| 53 | + options = regexprep(options, '\$f', ['''' jsonfile '''']); |
| 54 | + options = regexprep(options, '\$u', couchdburl); |
| 55 | + options = regexprep(options, '\$d', dbname); |
| 56 | + options = regexprep(options, '\$s', docname); |
| 57 | + [status, response] = system(options); |
| 58 | + if (status ~= 0) |
| 59 | + error('command failed:\n%s\n', response); |
| 60 | + end |
| 61 | +end |
0 commit comments