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

Idiom #92 Save object into JSON file

Write content of object x into file data.json.

import std.file, std.json;
auto x = JSONValue(["age":42, "name":"Bob"]);
"data.json".write(x.toJSON);
import 'dart:io' show File;
import 'dart:convert' show JSON;
await new File('data.json').writeAsString(JSON.encode(x));
import "encoding/json"
import "io/ioutil"
buffer, err := json.MarshalIndent(x, "", "  ")
if err != nil {
	return err
}
err = ioutil.WriteFile("data.json", buffer, 0644)
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)?

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org

Related idioms