簡體   English   中英

將 JSON 對象字符串數組轉換為 JS 對象數組

[英]Convert array of JSON object strings to array of JS objects

我想將 JSON 字符串數組轉換為 JSON 對象數組,而不需要遍歷每個項目並使用 JSON.parse 對其進行解析。

例子:

var s=[
  '{"Select":"11", "PhotoCount":"12"}',
  '{"Select":"21", "PhotoCount":"22"}',
  '{"Select":"31", "PhotoCount":"32"}'];

如果您有一個 JS JSON 對象數組:

var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];

並且你想要一個對象數組:

// JavaScript array of JavaScript objects
var objs = s.map(JSON.parse);

// ...or for older browsers
var objs=[];
for (var i=s.length;i--;) objs[i]=JSON.parse(s[i]);

// ...or for maximum speed:
var objs = JSON.parse('['+s.join(',')+']');

請參閱瀏覽器比較的速度測試


如果您有一個表示對象數組的 JSON 字符串:

var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';

並且你想要一個對象數組:

// JavaScript array of JavaScript objects
var objs = JSON.parse(s);

如果您有一組對象:

// A JavaScript array of JavaScript objects
var s = [{"Select":"11", "PhotoCount":"12"},{"Select":"21", "PhotoCount":"22"}];

......並且你想要它的 JSON 表示,然后:

// JSON string representing an array of objects
var json = JSON.stringify(s);

……或者如果你想要一個 JSON 字符串的 JavaScript 數組,那么:

// JavaScript array of strings (that are each a JSON object)
var jsons = s.map(JSON.stringify);

// ...or for older browsers
var jsons=[];
for (var i=s.length;i--;) jsons[i]=JSON.stringify(s[i]);
var json = jQuery.parseJSON(s); //If you have jQuery.

由於注釋看起來很雜亂,請在將這些方括號括在引號內后使用 parse 函數。

var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];

把上面的代碼改成

var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';

例如:

$(document).ready(function() {
    var s= '[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';

    s = jQuery.parseJSON(s);

    alert( s[0]["Select"] );
});

然后使用解析函數。 它肯定會起作用。

編輯:非常抱歉,我給出了錯誤的函數名稱。 它是 jQuery.parseJSON

查詢

json api

編輯(2020 年 4 月 30 日):

編輯,因為我得到了這個答案的贊成票。 有一個瀏覽器本機函數可以代替 JQuery(對於非 JQuery 用戶), JSON.parse("<json string here>")

如果你真的有:

var s = ['{"Select":"11", "PhotoCount":"12"}','{"Select":"21", "PhotoCount":"22"}'];

然后簡單地:

var objs = $.map(s, $.parseJSON);

這是一個演示。

暫無
暫無

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

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