简体   繁体   English

将逗号分隔的json对象列表转换为数组

[英]Converting a comma separated list of json objects to an array

I have a problem with a received javascript object. 我收到的javascript对象有问题。 I receive something like this: 我收到这样的东西:

{
 "name":"a",
 "surname":"b"
},
{
 "name":"c",
 "surname":"d"
},
{
 "name":"e",
 "surname":"f"
}

I store it in a variable and I would like to have an array of json objects, ie a JSON Array . 我将它存储在一个变量中,我希望有一个json对象数组,即一个JSON数组。

[{ "name":"a", "surname":"b" }, { "name":"c", "surname":"d" }, { "name":"e", "surname":"f" }] [{“name”:“a”,“surname”:“b”},{“name”:“c”,“surname”:“d”},{“name”:“e”,“surname”: “F” }]

I would need something as array.push() but I can't do it if I don't split the file before. 我需要一些像array.push(),但如果我之前没有拆分文件,我不能这样做。

This is an invalid notation - either JavaScript object or JSON. 这是一种无效的表示法 - JavaScript对象或JSON。 If you can fix your input or can make someone fix it, then it is definitely better to make your data source be valid. 如果您可以修改输入或者可以让某人修复它,那么使数据源有效肯定会更好。

However, sometimes we have to work with wrong data (external providers etc.), then you can make it a valid JSON array by adding a couple brackets in the beginning and the end: 但是,有时我们必须处理错误的数据(外部提供程序等),然后您可以通过在开头和结尾添加几个括号使其成为有效的JSON数组:

 var str = '{ "name":"a", "surname":"b" }, { "name":"c", "surname":"d" }, { "name":"e", "surname":"f" }'; var arr = JSON.parse("[" + str + "]"); //console.log(arr); for (var i = 0; i < arr.length; i++) { console.log("Name #" + (i + 1) + ": " + arr[i].name); console.log("Surname #" + (i + 1) + ": " + arr[i].surname); } 

It can look a little bit hacky, but it is the best thing you can do when you have to work with such input. 它可能看起来有点hacky,但是当你必须使用这样的输入时,这是你能做的最好的事情。
It looks much better than trying to split an object by commas manually, at least for me. 它看起来比尝试手动分割对象要好得多,至少对我而言。

I have one function to split your Array of Objects in many Arrays as you want, see the code :) 我有一个函数可以根据需要拆分多个数组中的对象数组,请参阅代码:)

var BATCH_SIZE = 2;

var fullList = [{name:"a",surname:"e"},{name:"a",surname:"e"}
  , {name:"a",surname:"e"},{name:"a",surname:"e"}, {name:"a",surname:"e"}];

Batchify(fullList,BATCH_SIZE);

function Batchify(fullList,BATCH_SIZE){
    var batches = [];
    var currentIndex = 0;
    while (currentIndex < fullList.length) {
       var sliceStart = currentIndex;
       var sliceEnd = currentIndex + BATCH_SIZE;
       batches.push(fullList.slice(sliceStart, sliceEnd));
       currentIndex += BATCH_SIZE;
    }
    console.log(batches);
}

I have example of code in JSfiddle , I hope solve your problem! 我在JSfiddle中有代码示例 ,希望能解决您的问题! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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