When i have an object with a nested object within, whose keys are numbers and send it to my node.js server, then the nested object is converted to an array. How can i prevent this ?
Client:
$.ajax({
url : `/cctool/report`,
method : "PUT",
data : {
new : {
10 : "Test",
20 : "Hello",
}
}
});
Server:
router.put("/cctool/report", (request, response) => {
console.log(request.body);
}
{ new: [ ‘Test’, ‘Hello’ ] }
When i add a not numeric key, everything works fine. Also when the keys are at the first level.
My settings:
const express = require('express');
const CookieParser = require('cookie-parser');
const Sessions = require('express-session');
const crypto = require('crypto');
const router = express.Router();
router.use(express.json());
router.use(express.urlencoded({extended : true}));
router.use(CookieParser());
router.use( Sessions({
secret : crypto.randomBytes(64).toString('hex'),
saveUninitialized : false,
cookie : {maxAge : 1000 * 60 * 60 * 8}, // 8 hours
resave : false
}));
2
Answers
You have to use a String value as a key, if you want to use a number you have to convert it to String type.
Source: https://tc39.es/ecma262/#sec-object-type
Try adding the
contentType
header and usingJSON.stringify
to serialize the object before passing to$.ajax
:See jQuery posting JSON.