<!--
{
  "availability" : [
    "iOS: 8.0.0 -",
    "iPadOS: 8.0.0 -",
    "macCatalyst: 8.0.0 -",
    "macOS: 10.10.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Foundation",
  "identifier" : "/documentation/Foundation/JSONEncoder/encode(_:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "s:10Foundation11JSONEncoderC6encodeyAA4DataVxKSERzlF"
  },
  "title" : "encode(_:)"
}
-->

# encode(_:)

Returns a JSON-encoded representation of the value you supply.

```
func encode<T>(_ value: T) throws -> Data where T : Encodable
```

## Parameters

`value`

The value to encode as JSON.

## Return Value

The encoded JSON data.

## Discussion

If there’s a problem encoding the value you supply, this method throws an error based on the type of problem:

- The value fails to encode, or contains a nested value that fails to encode—this method throws the corresponding error.
- The value isn’t encodable as a JSON array or JSON object—this method throws the <doc://com.apple.documentation/documentation/Swift/EncodingError/invalidValue(_:_:)> error.
- The value contains an exceptional floating-point number (such as <doc://com.apple.documentation/documentation/Swift/FloatingPoint/infinity> or <doc://com.apple.documentation/documentation/Swift/FloatingPoint/nan>) and you’re using the default [`JSONEncoder.NonConformingFloatEncodingStrategy`](/documentation/Foundation/JSONEncoder/NonConformingFloatEncodingStrategy-swift.enum) — this method throws the <doc://com.apple.documentation/documentation/Swift/EncodingError/invalidValue(_:_:)> error.

---

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)