title: How to create JSON from a dictionary in Swift 4?
body: <p>Edit: I have read the other answers on SO for the same issue , however Im unable to get the desired output. I have tried many variations as suggested in other questions but its not working.</p>
  <p>I have a JSON snipped which needs to be added as the body when I open a websocket.</p>
  <pre><code>sender: &quot;system1@example.com&quot;,
  recipients:&quot;system2@example.com&quot;,
  data: {
      text: &quot;Test Message&quot;
  },
  </code></pre>
  <p>So using Swift I did the following,</p>
  <pre><code>var messageDictionary : [String: Any] = [
      &quot;sender&quot;: &quot;system1@example.com&quot;,
      &quot;recipients&quot;:&quot;system2@example.com&quot;,
      &quot;data&quot;: [
          &quot;text&quot;: &quot;Test Message&quot;
      ],
  ]
  do {
      let jsonData = try JSONSerialization.data(withJSONObject: messageDictionary, options: .prettyPrinted)
      let jsonString = String(data: jsonData, encoding: String.Encoding.ascii)
      socket.write(string: jsonString!)
      print(jsonString)
  } catch {
      print(error.localizedDescription)
  }
  </code></pre>
  <p>When I print the jsonString, I get</p>
  <pre><code>Optional(&quot;{\n  \&quot;sender\&quot; : \&quot;system1@example.com\&quot;,\n  \&quot;data\&quot; : {\n    
      \&quot;text\&quot; : \&quot;Test Message\&quot;\n  },\n  \&quot;recipients\&quot; : 
      \&quot;system2@example.com\&quot;\n}&quot;)
  </code></pre>
  <p>as the console output. I expected the above snippet to be formatted as JSON.
  How to get the output as normal JSON without the /n and additional spaces?
  Im using Swift 4 and Xcode 9.1</p>
  <p><strong>Edit 2</strong>:</p>
  <p>let jsonData = try JSONSerialization.data(withJSONObject: messageDictionary, options: [])
  let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])</p>
  <p>I tried doing the above and I get the following as the output:</p>
  <pre><code>{
      data =     {
          text = Test Message;
      };
      recipients = &quot;system1@example.com&quot;;
      sender = &quot;system2@example.com&quot;;
  }
  </code></pre>
  <p>However the websocket expects this:</p>
  <pre><code>{ &quot;sender&quot;:&quot;system1@example.com&quot;,&quot;recipients&quot;:
  [&quot;system2@example.com&quot;],&quot;data&quot;:{&quot;text&quot;:&quot;Test Message&quot;}}
  </code></pre>
  <p>Even with a slight variation like misplacing of double quotes the websocket server doesnt accept the input. How to exactly format the JSOn this way so that the websocket can accept it?</p>