Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #92 Save object into JSON file

Write the contents of the object x into the file data.json.

import std.file, std.json;
auto x = JSONValue(["age":42, "name":"Bob"]);
"data.json".write(x.toJSON);
(require '[clojure.java.io :refer [file]])
(require '[jsonista.core :refer [write-value]])
(write-value (file "data.json") x)
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;
await File.WriteAllTextAsync("data.json", JsonSerializer.Serialize(x));	
import 'dart:io' show File;
import 'dart:convert' show JSON;
class JsonModel {
  // Create Field
  int id;
  String qrText, licen, trans, name;

//   // Constructor
//   JsonModel(
//       int idInt, String nameString, String userString, String passwordString) {
// //     id=idInt;
// // name =nameString;
// // user =userString;
// // password = passwordString;
//   }

  JsonModel(this.id, this.name, this.licen, this.trans, this.qrText);

  JsonModel.fromJson(Map<String, dynamic> parseJSON) {
    id = int.parse(parseJSON['id']);
    licen = parseJSON['Li
import "encoding/json"
import "os"
buffer, err := json.MarshalIndent(x, "", "  ")
if err != nil {
	return err
}
err = os.WriteFile("data.json", buffer, 0644)
import groovy.json.JsonBuilder
new File("data.json").text = new JsonBuilder(x).toPrettyString()
const fs = require('fs');
fs.writeFileSync('data.json', JSON.stringify(x));
(ql:quickload :yason)
(with-open-file (out "data.json" :direction :output)
  (yason:encode-plist x out))
cjson = require("cjson")
file = io.open("data.json", "w")
file:write(cjson.encode(x))
file:close()
file_put_contents('data.json', json_encode($x));
uses fpjsonrtti, classes;
var
  str: TMemoryStream;
  jss: string;
begin
  with TJSONStreamer.Create(nil) do try
    str := TMemoryStream.Create;
    try
      jss := ObjectToJSONString(x);
      str.Write(jss[1], length(jss));
      str.SaveToFile('data.json');
    finally
      str.Free;
    end;
  finally
    Free;
  end;
end.
use File::Slurp;
use JSON;
write_file('data.json', encode_json($x));
import json
with open("data.json", "w") as output:
    json.dump(x, output)
require "json"
x = {:hello => "goodbye"}

File.open("data.json", "w") do |f|
  f.puts(x.to_json)
end
extern crate serde_json;
#[macro_use] extern crate serde_derive;

use std::fs::File;
::serde_json::to_writer(&File::create("data.json")?, &x)?

New implementation...
< >
programming-idioms.org