<!--
{
  "availability" : [
    "iOS: 5.0.0 -",
    "iPadOS: 5.0.0 -",
    "macCatalyst: 13.1.0 -",
    "macOS: 10.7.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Foundation",
  "identifier" : "/documentation/Foundation/JSONSerialization/data(withJSONObject:options:)",
  "metadataVersion" : "0.1.0",
  "role" : "Type Method",
  "symbol" : {
    "kind" : "Type Method",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "c:objc(cs)NSJSONSerialization(cm)dataWithJSONObject:options:error:"
  },
  "title" : "data(withJSONObject:options:)"
}
-->

# data(withJSONObject:options:)

Returns JSON data from a Foundation object.

```
class func data(withJSONObject obj: Any, options opt: JSONSerialization.WritingOptions = []) throws -> Data
```

## Parameters

`obj`

The object from which to generate JSON data. Must not be `nil`.

`opt`

Options for creating the JSON data.

    See [`JSONSerialization.WritingOptions`](/documentation/Foundation/JSONSerialization/WritingOptions)     for possible values.

## Return Value

JSON data for `obj`, or `nil` if an internal error occurs. The resulting data is encoded in UTF-8.

## Discussion

If `obj` can’t produce valid JSON, [`JSONSerialization`](/documentation/Foundation/JSONSerialization) throws an exception. This exception occurs prior to parsing and represents a programming error, not an internal error. Before calling this method, you should check whether the input can produce valid JSON by using [`isValidJSONObject(_:)`](/documentation/Foundation/JSONSerialization/isValidJSONObject(_:)).

Setting the [`prettyPrinted`](/documentation/Foundation/JSONSerialization/WritingOptions/prettyPrinted) option generates JSON with white space designed to make the output more readable. If this option isn’t set, [`JSONSerialization`](/documentation/Foundation/JSONSerialization) generates the most compact possible JSON.

> Handling Errors in Swift:
> In Swift, this method returns a nonoptional result and is marked with the `throws` keyword to indicate that it throws an error in cases of failure.
> 
> You call this method in a `try` expression and handle any errors in the `catch` clauses of a `do` statement, as described in [Error Handling](https://docs.swift.org/swift-book/LanguageGuide/ErrorHandling.html) in [The Swift Programming Language](https://docs.swift.org/swift-book/) and `About Imported Cocoa Error Parameters`.

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)