javascript字符串到json对象的数组

时间:2018-05-04 15:17:44

标签: javascript arrays json

我有这个数组:

>>> sorted(['Aaaa', 'bbbb', 'cbaaa', 'bcaaa'], key=lambda s: s.lower())
['Aaaa', 'bbbb', 'bcaaa', 'cbaaa']

如何使它成为像这样的JSON对象:

data = [
    "Id = 2",
    "time = 10:59",
    "Topic = xxxxxxxxxxxxxxxx",
    "GUEST3",
    "Role = GS",
    "Infos = Connecticut",
    "GUEST4",
    "Role = HS",
    "Infos = Delaware",
    "GUEST5",
    "Role = CS",
    "Infos = Hawaii"
]   

3 个答案:

答案 0 :(得分:4)

以下是一些可以执行此操作的代码。

我已经对代码进行了评论,但基本要点是它会查看数组中的每个字符串,然后确定它是键和值还是另一层到对象中。

const data = ["Id = 2", "time = 10:59", "Topic = xxxxxxxxxxxxxxxx", "GUEST3", "Role = GS", "Infos = Connecticut", "GUEST4", "Role = HS", "Infos = Delaware", "GUEST5", "Role = CS", "Infos = Hawaii"];

// Declaring new object
let obj = {};
// Place to remember current level of object
let level;

// For every bit of the array
for (let item of data) {
  // If it contains an equals
  if (item.includes('=')) {
    // Split it into two stings
    let split = item.split('=');
    let key = split[0].trim();
    let cont = split[1].trim();
    // If we're already on a lower level like GUEST3 put it in there
    if (level) {
      obj[level][key] = cont
    } else {
      // Or just place the new data at the top level
      obj[key] = cont
    }
  } else {
    // If there's no equals we want to go down a layer
    level = item;
    obj[item] = {};
  }
}

console.log(obj)

我希望如果您努力了解发生的事情,请随时发表评论。

修改

我把你得到的三个答案混合起来做了一些更好的答案。

const data = ["Id = 2", "time = 10:59", "Topic = xxxxxxxxxxxxxxxx", "GUEST3", "Role = GS", "Infos = Connecticut", "GUEST4", "Role = HS", "Infos = Delaware", "GUEST5", "Role = CS", "Infos = Hawaii"]

let aO = o = {};
data.map(a => a.split(' = ')).forEach(e => {e.length > 1 ? aO[e[0]] = e[1] : aO = o[e] = {}});
console.log(o);

答案 1 :(得分:3)

注意:您的输入数组看起来非常不寻常且非标准。如果这确实是您收到数据的方式,那么您可以使用下面的代码来处理它。但是,我建议您进行双重检查,如果可能,请尝试更改后端(或此数据来自何处)以提供标准JSON字符串或JavaScript对象。



var data = [
  "Id = 2",
  "time = 10:59",
  "Topic = xxxxxxxxxxxxxxxx",
  "GUEST3",
  "Role = GS",
  "Infos = Connecticut",
  "GUEST4",
  "Role = HS",
  "Infos = Delaware",
  "GUEST5",
  "Role = CS",
  "Infos = Hawaii"
];

var result = {};
var putInto = result;
for (let token of data) {
  if (token.indexOf('=') != -1) {
    let nameValue = token.split('=');
    let name = nameValue[0].trim();
    let value = nameValue[1].trim();
    putInto[name] = value;
  } else {
    let child = {};
    result[token] = child;
    putInto = child;
  }
}

console.log(result)




答案 2 :(得分:1)

首先,您需要正确格式化数据。一种方法是制作它和数组数组。

const str =  ["Id = 2","time = 10:59","Topic = xxxxxxxxxxxxxxxx","GUEST3","Role = GS" ,"Infos = Connecticut","GUEST4","Role = HS","Infos = Delaware","GUEST5","Role = CS","Infos = Hawaii"]

const formatted = str.map(e => e.split('='))

然后您可以使用来自lodash

_.fromPairs之类的内容
const obj = _.fromPairs(formatted);

你有一个PLAIN json。这不完全是你需要的,但你可以从这开始。