简体   繁体   中英

Convert a string representation of an array to a JS array

I am converintg a legacy database and it currently stores the user roles as a string that looks like this:

["ADMIN", "MANAGER", "USER"]

I need to be able to convert this to an array in my response i send from express.

I currently have:

userRouter.get('/getAllUsers', (req, res) => {
    const errors = validationResult(req)
    if (!errors.isEmpty())
        return res.status(422).json(errors.array())
    userService.getUsers()
        .then(users => res.status(200).json({
            exception: false,
            payload: users.map(user => ({
                ...user,
                params: JSON.parse(user.params)
            }))
        }));
})

but this is giving me an error:

Unhandled rejection TypeError: Converting circular structure to JSON
    at JSON.stringify (<anonymous>)
    at stringify (/mnt/c/Development/tendesign/lfc-v2/node_modules/express/lib/response.js:1119:12)
    at ServerResponse.json (/mnt/c/Development/tendesign/lfc-v2/node_modules/express/lib/response.js:260:14)
    at /mnt/c/Development/tendesign/lfc-v2/dist/routers/user.router.js:21:57
    at tryCatcher (/mnt/c/Development/tendesign/lfc-v2/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (/mnt/c/Development/tendesign/lfc-v2/node_modules/bluebird/js/release/promise.js:512:31)
    at Promise._settlePromise (/mnt/c/Development/tendesign/lfc-v2/node_modules/bluebird/js/release/promise.js:569:18)
    at Promise._settlePromise0 (/mnt/c/Development/tendesign/lfc-v2/node_modules/bluebird/js/release/promise.js:614:10)
    at Promise._settlePromises (/mnt/c/Development/tendesign/lfc-v2/node_modules/bluebird/js/release/promise.js:693:18)
    at Async._drainQueue (/mnt/c/Development/tendesign/lfc-v2/node_modules/bluebird/js/release/async.js:133:16)
    at Async._drainQueues (/mnt/c/Development/tendesign/lfc-v2/node_modules/bluebird/js/release/async.js:143:10)
    at Immediate.Async.drainQueues [as _onImmediate] (/mnt/c/Development/tendesign/lfc-v2/node_modules/bluebird/js/release/async.js:17:14)
    at runCallback (timers.js:763:18)
    at tryOnImmediate (timers.js:734:5)
    at processImmediate (timers.js:716:5)

when I console.log(users) before processing, I get this:

[ user {
    dataValues:
     { id: 706,
       name: 'Sandra Will',
       email: 'sandra@design.us',
       params: '["ADMIN", "MANAGER", "USER"]',
       active: '1' },
    _previousDataValues:
     { id: 706,
       name: 'Sandra Will',
       email: 'sandra@design.us',
       params: '["ADMIN", "MANAGER", "USER"]',
       active: '1' },
    _changed: {},
    _modelOptions:
     { timestamps: false,
       validate: {},
       freezeTableName: false,
       underscored: false,
       underscoredAll: false,
       paranoid: false,
       rejectOnEmpty: false,
       whereCollection: null,
       schema: null,
       schemaDelimiter: '',
       defaultScope: {},
       scopes: [],
       indexes: [],
       name: [Object],
       omitNull: false,
       sequelize: [Sequelize],
       hooks: {},
       uniqueKeys: {} },
    _options:
     { isNewRecord: false,
       _schema: null,
       _schemaDelimiter: '',
       raw: true,
       attributes: [Array] },
    __eagerlyLoadedAssociations: [],
    isNewRecord: false },
  user {
    dataValues:
     { id: 710,
       name: 'Tommy Craw',
       email: 'thomas.craw@cargo.com',
       params: '["ADMIN", "MANAGER", "USER"]',
       active: '1' },
    _previousDataValues:
     { id: 710,
       name: 'Tommy Craw',
       email: 'thomas.craw@cargo.com',
       params: '["ADMIN", "MANAGER", "USER"]',
       active: '1' },
    _changed: {},
    _modelOptions:
     { timestamps: false,
       validate: {},
       freezeTableName: false,
       underscored: false,
       underscoredAll: false,
       paranoid: false,
       rejectOnEmpty: false,
       whereCollection: null,
       schema: null,
       schemaDelimiter: '',
       defaultScope: {},
       scopes: [],
       indexes: [],
       name: [Object],
       omitNull: false,
       sequelize: [Sequelize],
       hooks: {},
       uniqueKeys: {} },
    _options:
     { isNewRecord: false,
       _schema: null,
       _schemaDelimiter: '',
       raw: true,
       attributes: [Array] },
    __eagerlyLoadedAssociations: [],
    isNewRecord: false },
  user {
    dataValues:
     { id: 711,
       name: 'LeeAnne',
       email: 'leeanne.craw@cargo.com',
       params: '["ADMIN", "MANAGER", "USER"]',
       active: '1' },
    _previousDataValues:
     { id: 711,
       name: 'LeeAnne',
       email: 'leeanne.craw@cargo.com',
       params: '["ADMIN", "MANAGER", "USER"]',
       active: '1' },
    _changed: {},
    _modelOptions:
     { timestamps: false,
       validate: {},
       freezeTableName: false,
       underscored: false,
       underscoredAll: false,
       paranoid: false,
       rejectOnEmpty: false,
       whereCollection: null,
       schema: null,
       schemaDelimiter: '',
       defaultScope: {},

Just parse it.

 const dbStr = '["ADMIN", "MANAGER", "USER"]'; const array = JSON.parse(dbStr); console.log(array) 

Converting circular structure to JSON means that the parser is getting stuck in a loop because a property points to a parent object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM