admin管理员组

文章数量:1336631

I am creating one script where I want some dummy data to send to redis server using streams. For that, I am using "ioredis" module for Redis stream. Its working fine when I send simple key value structure i.e {a:"hello",b:"world"}.

But not working for Json array structure.

{
    "name": "abc",
    "ts": 123,
    "lists": [{
        "oil": "1",
        "food": "1,
        "item": "1"
    }]

}

It throws errors like

throw new Error(`Data type of property ${key} is not supported.`);

I am creating one script where I want some dummy data to send to redis server using streams. For that, I am using "ioredis" module for Redis stream. Its working fine when I send simple key value structure i.e {a:"hello",b:"world"}.

But not working for Json array structure.

{
    "name": "abc",
    "ts": 123,
    "lists": [{
        "oil": "1",
        "food": "1,
        "item": "1"
    }]

}

It throws errors like

throw new Error(`Data type of property ${key} is not supported.`);
Share Improve this question asked Jul 27, 2022 at 3:55 shubh gaikwadshubh gaikwad 1873 silver badges12 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Redis Streams don't do JSON. They do allow key-value data to be associated with each event. Note that both the key and the value must be strings.

ioredis does this with variadic arguments for the keys and values. There's an example on the ioredis repo but here's the bit you probably care about:

client.xadd("user-stream", "*", "name", "John", "age", "20")

Node Redis has a different syntax that allows you to pass in a JavaScript object. But, that object must be flat and full of strings. There's an example on GitHub but here's the tl;dr:

client.xAdd('user-stream', '*', { name: "John", age: "20" })

Also, note, that in both cases, the function is async so you can await it if you like.

If you want to store JSON in an event in a Stream in Redis, you'll need to stringify it first:

const data = JSON.stringify({
  "name": "abc",
  "ts": 123,
  "lists": [{
    "oil": "1",
    "food": "1",
    "item": "1"
  }]
})

/* if you use ioredis */
client.xadd("user-stream", "*", "data", data)

/* if you use Node Redis */
client.xAdd('user-stream', '*', { data })

Hope this helps!

JSON is not a valid data type for Redis out of the box.

There are some alternatives.

  • You can serialize the JSON structure into a string and store that string into Redis. When you later recover it from Redis, you need to deserialize it into your JSON structure.

  • Include RedisJSON in your Redis installation. A module that provides JSON support in Redis.

Node Redis has a neat solution to this here. You might consider using the same in ioredis as follows:

const args = [];
for (const [key, value] of Object.entries(reportingRequest)) {
  args.push(key, value);
}
client.xadd(REDIS_STREAM_KEY, '*', ...args);

本文标签: javascriptHow to send JSON in Redis stream NodeJsStack Overflow