我怎么能把这个大字符串拆分成JavaScript中的几个字符串?

时间:2017-06-25 21:08:54

标签: javascript node.js

如何在javascript中将此字符串拆分为多个字符串? 我希望每个部分的不同字符串来自' {'到'},'

/////////////////////////////////////////////// ///////////////////////////

{
   "result" : [
      {
         "DimmerLevels" : "none",
         "IsDimmer" : false,
         "Name" : "bathroom",
         "SubType" : "X10",
         "Type" : "Lighting 1",
         "idx" : "1"
      },
      {
         "DimmerLevels" : "none",
         "IsDimmer" : false,
         "Name" : "dining room",
         "SubType" : "X10",
         "Type" : "Lighting 1",
         "idx" : "5"
      },
      {
         "DimmerLevels" : "none",
         "IsDimmer" : false,
         "Name" : "hall",
         "SubType" : "X10",
         "Type" : "Lighting 1",
         "idx" : "3"
      },
      {
         "DimmerLevels" : "none",
         "IsDimmer" : false,
         "Name" : "kitchen",
         "SubType" : "X10",
         "Type" : "Lighting 1",
         "idx" : "2"
      },
      {
         "DimmerLevels" : "none",
         "IsDimmer" : false,
         "Name" : "parking",
         "SubType" : "X10",
         "Type" : "Lighting 1",
         "idx" : "4"
      }
   ],
   "status" : "OK",
   "title" : "GetLightSwitches"
}

1 个答案:

答案 0 :(得分:0)

您可以尝试拆分字符串,但如果它是有效的JSON并且您只想为result中的每个项目使用字符串化的JSON,则只需解析JSON,遍历result中的项目,然后进行字符串化它们:

JSON.parse(string).result.map(item => JSON.stringify(item))

它会产生

[ '{"DimmerLevels":"none","IsDimmer":false,"Name":"bathroom","SubType":"X10","Type":"Lighting 1","idx":"1"}',
  '{"DimmerLevels":"none","IsDimmer":false,"Name":"dining room","SubType":"X10","Type":"Lighting 1","idx":"5"}',
  '{"DimmerLevels":"none","IsDimmer":false,"Name":"hall","SubType":"X10","Type":"Lighting 1","idx":"3"}',
  '{"DimmerLevels":"none","IsDimmer":false,"Name":"kitchen","SubType":"X10","Type":"Lighting 1","idx":"2"}',
  '{"DimmerLevels":"none","IsDimmer":false,"Name":"parking","SubType":"X10","Type":"Lighting 1","idx":"4"}' ]