You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JSON Schema Faker生成从0开始的自增ID?

Can JSON Schema Faker generate auto-incrementing IDs starting from 0?

Absolutely! You can definitely achieve auto-incrementing IDs starting at 0 with JSON Schema Faker—the default autoIncrement behavior starts at a random value, but a simple custom generator will let you take full control of the starting number.

Here's how to do it:

1. Use a closure-based counter for full control

The key is to maintain your own counter variable outside the schema, then use a custom generator function to increment it each time a new ID is generated. This ensures you start exactly at 0 and increment sequentially.

Example code:

const jsf = require('json-schema-faker');

// Initialize our counter starting at 0
let idCounter = 0;

// Define your schema with a custom ID generator
const userSchema = {
  type: 'object',
  properties: {
    id: {
      type: 'integer',
      // Custom generator: return current counter value, then increment
      'x-jsf': () => idCounter++
    },
    username: {
      type: 'string',
      faker: 'internet.userName'
    },
    email: {
      type: 'string',
      faker: 'internet.email'
    }
  },
  required: ['id', 'username', 'email']
};

// Generate 5 sample users to test
for (let i = 0; i < 5; i++) {
  const user = jsf.generate(userSchema);
  console.log(user);
}

This will output users with IDs 0, 1, 2, 3, 4—exactly what you're looking for.

2. Resetting the counter

If you need to restart the sequence from 0 later (e.g., for a new batch of data), just reset the counter variable:

idCounter = 0; // Now the next generated ID will be 0 again

Why the default autoIncrement uses a random start

The built-in autoIncrement feature starts at a random value by design—it's meant to avoid ID collisions if you're using multiple instances of JSON Schema Faker or generating data across different sessions. But for controlled, sequential IDs starting at 0, the custom counter method is the way to go.

内容的提问来源于stack exchange,提问作者Mateusz Cholewka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:50:49