WordPress能否存储JSON对象并通过REST API原样检索?
Absolutely, you can store raw JSON objects like [{name: 'hello', type: 'myself'}] in WordPress and retrieve them via the REST API without extra <pre>/<code> markup or escaped characters. Here are three practical approaches tailored to different use cases:
1. Use Custom Fields (Most Reliable)
This is the cleanest method because it separates your JSON data from the main post content, avoiding any editor formatting issues.
Step 1: Add the custom field
When editing a post, enable the "Custom Fields" panel (check it in the "Screen Options" dropdown at the top right of the editor). Create a new field (e.g.,raw_json_data) and paste your JSON directly into the value field. Pro tip: Fix any invalid JSON syntax first—standard JSON requires double quotes for keys/values, and no trailing commas like in your example.Step 2: Expose the field to the REST API
By default, custom fields aren't included in REST responses. Add this code to your theme'sfunctions.phpor a custom plugin to register the field:add_action('rest_api_init', function() { register_rest_field('post', 'raw_json_data', [ 'get_callback' => function($post) { $json_value = get_post_meta($post['id'], 'raw_json_data', true); // Return parsed JSON object, or raw string if parsing fails return json_decode($json_value, true) ?: $json_value; }, 'schema' => [ 'description' => 'Raw JSON data associated with the post', 'type' => 'object' // Use 'string' if you want to return the raw JSON text ] ]); });Now when you call
/wp-json/wp/v2/posts/{post_id}, you'll see araw_json_datafield in the response with your clean JSON (either as a parsed object or raw string, depending on your preference).
2. Extract JSON from Code Blocks (If You Must Use the Editor)
If you need to keep the JSON in the post content's code block, you can filter the REST API response to strip out the markup and unescape characters:
Add this snippet to your functions.php:
add_filter('rest_prepare_post', function($response, $post, $request) { $content = $post->post_content; // Match WordPress's default code block HTML structure preg_match('/<pre class="wp-block-code"><code>(.*?)<\/code><\/pre>/s', $content, $matches); if (!empty($matches[1])) { // Reverse HTML escaping and parse the JSON $clean_json = htmlspecialchars_decode($matches[1]); $response->data['extracted_json'] = json_decode($clean_json, true) ?: $clean_json; } return $response; }, 10, 3);
After adding this, your REST response will include an extracted_json field with the raw JSON, free of extra markup. Note: This relies on WordPress's code block output staying consistent—if the block's HTML changes in a future update, you may need to adjust the regex.
3. Custom Post Type for JSON-Only Content
If you're working with a lot of JSON data, create a dedicated custom post type to store entries:
add_action('init', function() { register_post_type('json_entries', [ 'public' => true, 'show_in_rest' => true, 'rest_base' => 'json-entries', 'supports' => ['title'], // Skip the editor if you only need to store JSON in the content field 'labels' => [ 'name' => 'JSON Entries', 'singular_name' => 'JSON Entry' ] ]); }); // Filter the REST response to return clean JSON add_filter('rest_prepare_json_entries', function($response, $post) { $response->data['raw_json'] = json_decode($post->post_content, true) ?: $post->post_content; return $response; }, 10, 2);
Create a new "JSON Entry" post, paste your JSON into the content field, and fetch it via /wp-json/wp/v2/json-entries/{entry_id}—the raw_json field will have your unmodified JSON.
Key Notes
- Always validate your JSON syntax (use tools like JSONLint) to avoid parsing errors.
- The custom fields method is the most robust long-term, as it insulates your data from editor or block changes.
内容的提问来源于stack exchange,提问作者GWorking

