title: How to select query's result to JSON in Rust and Nickel?
body: <p>I use nickel.rs:</p>
  
  <pre><code>router.get("/api/movies", middleware! { |request, response|
      let mut test_movies =
      r#"[
          { "title": "Ironman"},
          { "title": "The Walk"},
          { "title": "Paddington"}
      ]
      "#;
      let json = Json::from_str(test_movies);
      format!("{}", json.unwrap())
  });
  </code></pre>
  
  <p>I wanted to create JSON format. The code for connecting to PostgreSQL and converting to JSON definition is below:</p>
  
  <pre><code>extern crate rustc_serialize;
  use rustc_serialize::json::{Json, Parser};
  
  #[derive(RustcDecodable, RustcEncodable)]
  struct Movie {
      title: String,
  }
  </code></pre>
  
  <p>And I tried to select query and create JSON</p>
  
  <pre><code>router.get("/api/movies", middleware! { |request, response|
      let conn = Connection::connect("postgres://postgres@localhost", SslMode::None).unwrap();
      let stmt = match conn.prepare("select title from movie") {
          Ok(stmt) =&gt; stmt,
          Err(e) =&gt; {
              return response.send(format!("Preparing query failed: {}", e));
          }
      };
      let res = match stmt.execute(&amp;[]) {
          Ok(v) =&gt; println!("Selecting movie was Success."),
          Err(e) =&gt; println!("Selecting movie failed. =&gt; {:?}", e)
      };
  
      // ???
      // let movies = Json::from_obj(res);
      // let movies = request.json_as::&lt;&amp;[Movie]&gt;().unwrap();
      // let movies = request.json_as::Vec&lt;Movie&gt;().unwrap();
      format!("{}", movies)
  });
  </code></pre>
  
  <p>however, I have no idea how to convert the result to JSON.</p>
  
  <pre><code>let conn = conn.clone();
  </code></pre>
  
  <p>makes the errors.</p>
  
  <pre><code>error: no method named `clone` found for type `postgres::Connection` in the current scope
  </code></pre>
  
  <p>I added</p>
  
  <pre><code>use nickel::status::StatusCode;
  
  //use rustc_serialize::json::{Json, Parser};
  use rustc_serialize::{json};
  
  json::encode(&amp;movies).unwrap();
  </code></pre>
  
  <p>was work. but null returned...</p>
  
  <p><strong>Finally</strong></p>
  
  <p>I changed <code>execute</code> to <code>query</code> and also use <code>Vec&lt;Movie&gt;</code>.</p>
  
  <pre><code>let mut v: Vec&lt;Movie&gt; = vec![];
  let movies = &amp;conn.query("select title from movie", &amp;[]).unwrap();
  for row in movies {
      let movie = Movie {
          title: row.get(0),
      };
  
      v.push(movie);
  }
  
  let json_obj = json::encode(&amp;v).unwrap();
  response.set(MediaType::Json);
  response.set(StatusCode::Ok);
  return response.send(json_obj);
  </code></pre>
  
  <p>I also defined <code>struct</code> Moview like model</p>
  
  <pre><code>struct Movie {
      // id: i32,
      title: String,
  }
  </code></pre>
  
  <p>hmm.. troublesome a lot.</p>
  
  <p>however, I can't <code>conn.clone()</code> yet.</p>