簡體   English   中英

如何在NodeJS / JavaScript中將文本格式的JSON數組轉換為JSON對象數組?

[英]How to convert text format JSON array into JSON object array in NodeJS / JavaScript?

我有一個使用Node.JS和ExpressJS創建的REST API。 我需要從FrontEnd接收一個JSON數組到我的REST API中。

api.post('/save_pg13_app_list', function (req, res) {
        var app_list = {
            list_object: req.body.list_object
        };
        console.log(app_list.list_object);
        res.json({ type: "success", code: 200, data: app_list.list_object });
    });

這個list_object是我從前端獲得的JSON數組。

這是任務的POST端點。

HTTP://本地主機:7000 / API / admin_control_manage / save_pg13_app_list

這是我正在接收的數據對象:

{
 list_object :  "[{name:\"chanaka\",\"code\":10},{name:\"shashini\",code:19}]" 
}

當我在REST API中使用此list_object時,它是一個字符串對象。 現在,我需要將其解析為JSON。 因此,我使用以下代碼將其轉換為JSON。

var json_array = JSON.parse(app_list.list_object);

但是我得到這個錯誤:

POST / api / admin_control_manage / save_pg13_app_list 500 0.936 ms-1212語法錯誤:JSON中意外標記n在/home/chanaka/WebstormProjects/PostureAPI/app/routes/admin_control.js:210:26在Object.parse(本地)位置2處在Layer.handle [作為handle_request](/home/chanaka/WebstormProjects/PostureAPI/node_modules/express/lib/router/layer.js:95:5)在下一個(/ home / chanaka / WebstormProjects / PostureAPI / node_modules / express /位於Layer.handle的Route.dispatch(/home/chanaka/WebstormProjects/PostureAPI/node_modules/express/lib/router/route.js:112:3)處的lib / router / route.js:131:13)[as handle_request] (/home/chanaka/WebstormProjects/PostureAPI/node_modules/express/lib/router/layer.js:95:5)位於/home/chanaka/WebstormProjects/PostureAPI/node_modules/express/lib/router/index.js:277: 22在Function.process_params(/home/chanaka/WebstormProjects/PostureAPI/node_modules/express/lib/router/index.js:330:12)在下一個(/ home / chanaka / WebstormProjects / PostureAPI / node_modules / express / lib / router /index.js:271:10 )在Function.handle(/home/chanaka/WebstormProjects/PostureAPI/node_modules/express/lib/router/index.js:176:3)

我需要做的就是將[{name:"chanaka",code:10},{name:"shashini",code:19}]類型的字符串數組轉換為JSON。 這是怎么做的?

嘗試在回調函數中對對象進行字符串化;

res.json({ 
    type: "success", 
    code: 200, 
    data: JSON.stringify(app_list.list_object) 
});

JSON stringify將正確格式化它,以便正確解析

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM