---
title: "data(withJSONObject:options:)"
framework: foundation
role: symbol
role_heading: Type Method
path: "foundation/jsonserialization/data(withjsonobject:options:)"
---

# data(withJSONObject:options:)

Returns JSON data from a Foundation object.

## Declaration

```swift
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 doc://com.apple.foundation/documentation/Foundation/JSONSerialization/WritingOptions for possible values.

## Return Value

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

## Discussion

Discussion If obj can’t produce valid JSON, 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(_:). Setting the prettyPrinted option generates JSON with white space designed to make the output more readable. If this option isn’t set, JSONSerialization generates the most compact possible JSON. note: 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 in The Swift Programming Language and About Imported Cocoa Error Parameters.

## See Also

### Creating JSON Data

- [writeJSONObject(_:to:options:error:)](foundation/jsonserialization/writejsonobject(_:to:options:error:).md)
- [JSONSerialization.WritingOptions](foundation/jsonserialization/writingoptions.md)
- [isValidJSONObject(_:)](foundation/jsonserialization/isvalidjsonobject(_:).md)
