Builds a json export file for importing on the client
518443
public function export_to_client() {
        if(!Permission::check('CODE_BANK_ACCESS')) {
            return Security::permissionFailure($this);
        }
        
        
        //Bump up time limit we may need it
        set_time_limit(480);
        
        
        //Dump Data
        $languages=$this->queryToArray(DB::query('SELECT "ID", "Name", "FileExtension", "HighlightCode", "UserLanguage" FROM "SnippetLanguage"'));
        $snippets=$this->queryToArray(DB::query('SELECT "ID", "Title", "Description", "Tags", "LanguageID", "PackageID", "FolderID" FROM "Snippet"'));
        $versions=$this->queryToArray(DB::query('SELECT "ID", "Created", "Text", "ParentID" FROM "SnippetVersion"'));
        $packages=$this->queryToArray(DB::query('SELECT "ID", "Title" FROM "SnippetPackage"'));
        $folders=$this->queryToArray(DB::query('SELECT "ID", "Name", "ParentID", "LanguageID" FROM "SnippetFolder"'));
        
        
        //Build final response array
        $response=array(
                        'format'=>'ToClient',
                        'data'=>array(
                                    'languages'=>$languages,
                                    'snippets'=>$snippets,
                                    'versions'=>$versions,
                                    'packages'=>$packages,
                                    'folders'=>$folders
                                )
                    );
        
        
        //Send File
        SS_HTTPRequest::send_file(json_encode($response), date('Y-m-d_hi').'.cbexport', 'application/json')->output();
        
        
        //Save session and exit
        Session::save();
        exit;
    }
766050
function createJsonFileDiscoverProvider(hostsFile) {
    var fs = require('fs');

    return function jsonFileProvider(callback) {
        fs.readFile(hostsFile, function onFileRead(err, data) {
            if (err) {
                callback(err);
                return;
            }

            var hosts;
            try {
                hosts = JSON.parse(data.toString());
            } catch (e) {
                callback(e);
                return;
            }
            callback(null, hosts);
            return;
        });
    };
}
126621
def dump_json(testcase, json_file):
    
    logging.info("dump testcase to JSON format.")

    with io.open(json_file, 'w', encoding="utf-8") as outfile:
        my_json_str = json.dumps(testcase, ensure_ascii=ensure_ascii, indent=4)
        if isinstance(my_json_str, bytes):
            my_json_str = my_json_str.decode("utf-8")

        outfile.write(my_json_str)

    logging.info("Generate JSON testcase successfully: {}".format(json_file))
579360
function buildJSONSource() {

  var data = getModularSource();

  addCorePackage();
  prepareData();
  outputJSON('source.json', data);

  function addCorePackage() {
    data.modules.unshift({
      name: 'Core'
    });
    data.packages.unshift({
      name: 'Sugar',
      type: 'core',
      module: 'Core',
      dependencies: [],
      bodyWithComments: readFile('lib/core.js').trim()
    });
  }

  function bundleSetPackages() {
    var packages = [], handledSets = {}, p;

    for (var i = 0; i < data.packages.length; i++) {
      p = data.packages[i];
      if (p.set) {
        // If the package has been handled already then just skip.
        if (!handledSets[p.namespace + p.setName]) {
          packages.push({
            setName: p.setName,
            name: p.setName.replace(/[\[\]]/g, ''),
            sample: p.set.slice(0, 3).concat('...').join(', '),
            type: p.type,
            alias: p.alias,
            module: p.module,
            namespace: p.namespace,
            dependencies: p.dependencies,
            bodyWithComments: p.bodyWithComments
          });
          handledSets[p.namespace + p.setName] = true;
        }
      } else {
        packages.push(p);
      }
    }

    return packages;
  }

  function prepareData() {
    var bundledPackages = bundleSetPackages();
    data.modules.forEach(function(m) {
      indentField(m, 'comment');
    });
    bundledPackages.forEach(function(p) {

      // Pre-indenting all packages rather than doing it on compile to
      // save some cycles and also correctly calculate the package size.
      indentField(p, 'blockStart');
      indentField(p, 'blockEnd');
      indentField(p, 'bodyWithComments');

      cleanSourcePackage(p);
    });
    data.packages = bundledPackages;
  }

  function indentField(p, field) {
    if (p[field]) {
      p[field] = p[field].replace(/^(?=.)/gm, '  ');
    }
  }

  function cleanSourcePackage(p) {
    if (sourcePackageIsDependency(p)) {
      delete p.type;
    }
    delete p.vars;
    delete p.target;
    delete p.body;
    delete p.path;
    delete p.assigns;
    delete p.comments;
    delete p.defineMethod;
    delete p.varDependencies;
    compactField(p, 'bodyWithComments');
    compactField(p, 'dependencies');
  }

  function compactField(p, field) {
    var val = p[field];
    if (!val || (Array.isArray(val) && !val.length)) {
      delete p[field];
    }
  }

}
1353432
def concatenate_json(source_folder, destination_file):
    
    matches = []
    for root, dirnames, filenames in os.walk(source_folder):
        for filename in fnmatch.filter(filenames, '*.json'):
            matches.append(os.path.join(root, filename))

    with open(destination_file, "wb") as f:
        f.write("[\n")
        for m in matches[:-1]:
            f.write(open(m, "rb").read())
            f.write(",\n")
        f.write(open(matches[-1], "rb").read())
        f.write("\n]")
269836
def to_json(cls, config, compact=False, indent=2, level=0):
        
        lines = ""
        if isinstance(config, ConfigTree):
            if len(config) == 0:
                lines += '{}'
            else:
                lines += '{\n'
                bet_lines = []
                for key, item in config.items():
                    bet_lines.append('{indent}"{key}": {value}'.format(
                        indent=''.rjust((level + 1) * indent, ' '),
                        key=key.strip('"'),  # for dotted keys enclosed with "" to not be interpreted as nested key
                        value=cls.to_json(item, compact, indent, level + 1))
                    )
                lines += ',\n'.join(bet_lines)
                lines += '\n{indent}}}'.format(indent=''.rjust(level * indent, ' '))
        elif isinstance(config, list):
            if len(config) == 0:
                lines += '[]'
            else:
                lines += '[\n'
                bet_lines = []
                for item in config:
                    bet_lines.append('{indent}{value}'.format(
                        indent=''.rjust((level + 1) * indent, ' '),
                        value=cls.to_json(item, compact, indent, level + 1))
                    )
                lines += ',\n'.join(bet_lines)
                lines += '\n{indent}]'.format(indent=''.rjust(level * indent, ' '))
        elif isinstance(config, basestring):
            lines = json.dumps(config)
        elif config is None or isinstance(config, NoneValue):
            lines = 'null'
        elif config is True:
            lines = 'true'
        elif config is False:
            lines = 'false'
        else:
            lines = str(config)
        return lines
213362
def export_to_json(self):
        

        return {
            hostname: sorted(self._encode_key(key) for key in pins)
            for hostname, pins in self._storage.items()
        }
10696
def import_json(path, model, batch_len=100, db_alias='default', start_batch=0, end_batch=None, ignore_errors=False, verbosity=2):
    """"""

    # TODO: use a generator to save memory for large json files/databases
    if verbosity > 0:
        print('Reading json records (dictionaries) from {0}.'.format(repr(path)))
    item_list = json.load(open(path, 'r'))
    if verbosity > 0:
        print('Finished reading {0} items from {1}.'.format(len(item_list), repr(path)))
    import_items(item_list, model=model, batch_len=batch_len, db_alias=db_alias, start_batch=start_batch, end_batch=end_batch, ignore_errors=ignore_errors, verbosity=verbosity)
517147
def json(self):
        """"""
        d = { 'id': self.id, 'format': self.formatclass.__name__,'label': self.label, 'mimetype': self.formatclass.mimetype,  'schema': self.formatclass.schema }
        if self.unique:
            d['unique'] = True
        if self.filename:
            d['filename'] = self.filename
        if self.extension:
            d['extension'] = self.extension
        if self.acceptarchive:
            d['acceptarchive'] = self.acceptarchive
        #d['parameters'] = {}

        #The actual parameters are included as XML, and transformed by clam.js using XSLT (parameter.xsl) to generate the forms
        parametersxml = ''
        for parameter in self.parameters:
            parametersxml += parameter.xml()
        d['parametersxml'] = '<?xml version="1.0" encoding="utf-8" ?><parameters>' + parametersxml + '</parameters>'
        d['converters'] = [ {'id':x.id, 'label':x.label} for x in self.converters ]
        d['inputsources'] = [ {'id':x.id, 'label':x.label} for x in self.inputsources ]

        return json.dumps(d)
6366
def export(self, node):
        """"""
        dictexporter = self.dictexporter or DictExporter()
        data = dictexporter.export(node)
        return json.dumps(data, **self.kwargs)
120704
def to_json_file(graph: BELGraph, file: TextIO, **kwargs) -> None:
    """"""
    graph_json_dict = to_json(graph)
    json.dump(graph_json_dict, file, ensure_ascii=False, **kwargs)
563904
def export_net_json(net, net_type, indent='no-indent'):
  '''  '''
  import json
  from copy import deepcopy

  if net_type == 'dat':
    exp_dict = deepcopy(net.dat)

    if type(exp_dict['mat']) is not list:
      exp_dict['mat'] = exp_dict['mat'].tolist()
      if 'mat_orig' in exp_dict:
        exp_dict['mat_orig'] = exp_dict['mat_orig'].tolist()

  elif net_type == 'viz':
    exp_dict = net.viz

  elif net_type == 'sim_row':
    exp_dict = net.sim['row']

  elif net_type == 'sim_col':
    exp_dict = net.sim['col']

  # make json
  if indent == 'indent':
    exp_json = json.dumps(exp_dict, indent=2)
  else:
    exp_json = json.dumps(exp_dict)

  return exp_json
738968
def to_json_file(self, path, file_name=None):
        """"""
        if bool(path) and os.path.isdir(path):
            self.write_to_json(path, file_name)
        else:
            self.write_to_json(os.getcwd(), file_name)
1163716
def process_all_json_files(build_dir):
    """"""
    html_files = []
    for root, _, files in os.walk(build_dir):
        for filename in fnmatch.filter(files, '*.fjson'):
            if filename in ['search.fjson', 'genindex.fjson',
                            'py-modindex.fjson']:
                continue
            html_files.append(os.path.join(root, filename))
    page_list = []
    for filename in html_files:
        try:
            result = process_file(filename)
            if result:
                page_list.append(result)
        # we're unsure which exceptions can be raised
        except:  # noqa
            pass
    return page_list
410804
def generate_json_artifacts(app, pagename, templatename, context, doctree):
    
    try:
        # We need to get the output directory where the docs are built
        # _build/json.
        build_json = os.path.abspath(
            os.path.join(app.outdir, '..', 'json')
        )
        outjson = os.path.join(build_json, pagename + '.fjson')
        outdir = os.path.dirname(outjson)
        if not os.path.exists(outdir):
            os.makedirs(outdir)
        with open(outjson, 'w+') as json_file:
            to_context = {
                key: context.get(key, '')
                for key in KEYS
            }
            json.dump(to_context, json_file, indent=4)
    except TypeError:
        log.exception(
            'Fail to encode JSON for page {page}'.format(page=outjson)
        )
    except IOError:
        log.exception(
            'Fail to save JSON output for page {page}'.format(page=outjson)
        )
    except Exception as e:
        log.exception(
            'Failure in JSON search dump for page {page}'.format(page=outjson)
        )
745606
def Import(context, request):
    
    errors = []
    logs = []

    # Do import stuff here
    logs.append("Generic XML Import is not available")

    results = {'errors': errors, 'log': logs}
    return json.dumps(results)
556460
def import_json(cls, filename):
        
        with open(filename, 'rb') as f:
            json_graph = f.read().decode('utf-8')
        return cls.from_json(json_graph)