将String转换为JSON对象

时间:2017-07-22 18:31:34

标签: javascript json

是否可以使用JavaScript转换这样的字符串:

"Product : Bike , 2005 : $12000,2006 : $13000,2007 : $14000,2008 : $15000"

到这样的JSON对象:

{
    "Product":"Bike",
    "2005" : $12000,
    "2006" : $13000,
    "2007" : $14000,
    "2008" : $15000
}

4 个答案:

答案 0 :(得分:1)

假设你的字符串的结构是相同的,用,分割将给你一组键/值对,然后用:分割每一对你将得到键和值。

var str = "Product : Bike , 2005 : $12000,2006 : $13000,2007 : $14000,2008 : $15000"
var obj={};
str.split(",").forEach(function(item){
    var keyVal = item.split(":")
    obj[keyVal[0].trim()] = keyVal[1].trim()
})
console.log(obj)

答案 1 :(得分:1)

您可split ,:上的字符串trim。请确保var string = "Product : Bike , 2005 : $12000,2006 : $13000,2007 : $14000,2008 : $15000"; var result = {}; var duplets = string.split(','); for (var i = 0; i < duplets.length; i++) { var duplet = duplets[i]; var values = duplet.split(':'); result[values[0].trim()] = values[1].trim(); } console.log(result);生成的字符串,因为条款周围还有空格。

var string = "Product : Bike , 2005 : $12000,2006 : $13000,2007 : $14000,2008 : $15000";
var regex = /(?:^|,)([^,:]+):([^,]+)(?=$|,)/g;

var result = {};
while(match = regex.exec(string)) {
  result[match[1].trim()] = match[2].trim();
}
console.log(result);

您还可以使用正则表达式:

(?:^|,)

以下是有关正则表达式的一些信息:

  • ^匹配字符串的开头(,)或([^,:]+):
  • ,多次匹配除::以外的所有字符,直到下一个([^,]+)(?=$|,)并形成第一个选择组
  • ,多次匹配除$以外的所有字符,直至字符串,或下一个{{1}}的结尾。它形成了第二个匹配组。

答案 2 :(得分:1)

使用replace() with RegExp

细分,regular expression匹配如下:

  1. \s*任意数量的空白(包括无)
  2. 后跟(\:|,){1} 1 1冒号或\s*逗号
  3. capture group
  4. 后跟g任意数量的空格(包括无)
  5. 然后标志$1强制匹配所有匹配项,直到字符串结束。
  6. 匹配由被引号"包围的捕获值const str = "Product : Bike , 2005 : $12000,2006 : $13000,2007 : $14000,2008 : $15000", json_str = '{"' + str.replace( /\s*(\:|,){1}\s*/g, '"$1"' ) + '"}', js_object = JSON.parse( json_str ); console.log( json_str ); // transportable console.log( js_object ); // useable替换。

    这会导致修剪属性名称和值周围的所有前导和尾随空格,并正确引用属性名称和值。
    然后,我们只需要在字符串的任一端添加引号和大括号,使其成为有效的JSON字符串,准备好parse()到对象中。

    &#13;
    &#13;
    //pull html buttons
    var playBtn = document.getElementById("playBtn");
    var pauseBtn = document.getElementById("pauseBtn");
    var stopBtn = document.getElementById("stopBtn");
    var backBtn = document.getElementById("backBtn");
    var nextBtn = document.getElementById("nextBtn");
    var index = 0
    //make as JukeBox constructor 
    function Jukebox(){
        this.jamz = []
    }
    
    //be able to add songs to the jukebox
    Jukebox.prototype.addSong = function(songs){
        this.jamz.push(songs);
    }
    
    //test audio in console log
    /*Jukebox.prototype.play = function(){
        var playSong = this.jamz;
        console.log(this.jamz)
    }*/
    
    //Be able to push songs into the jukebox. 
    //first create a "new" jukebox
    var jukebox = new Jukebox();
    
    //use the previous prototype to add songs 
    
    jukebox.addSong(new Audio("audio/Young M.A - OOOUUU.mp3"));
    jukebox.addSong(new Audio("audio/J Balvin - Safari.mp3"));
    jukebox.addSong(new Audio("audio/Marshmello x Ookay - Chasing Colors.mp3"));
    jukebox.addSong(new Audio("audio/Bryson Tiller - Run Me Dry.mp3"));
    jukebox.addSong(new Audio("audio/Midnight To Monaco - One In A 
    Million.mp3"));
    
    
    //give each button a method 
    
    Jukebox.prototype.play = function(){
        this.jamz[index].play();
    }
    
    Jukebox.prototype.pause = function(){
        this.jamz[index].pause();
    }
    
    Jukebox.prototype.stop = function(){
        this.jamz[index].stop();
    }
    //figured out next button functionality through indexes. go back up top to 
    variables and create and index variable
    Jukebox.prototype.next= function(){
        this.jamz[index].pause(),
        index++;
        this.jamz[index].currentTime= 0,
        this.jamz[index].play;
        if (index ==this.jamz.length){
            this.index.currentTime = 0;
            this.jamz[index].play();
        }
    };
    
    //same functionality as "next except" if statement index will = 0
    
    Jukebox.prototype.back = function() {
      this.jamz[index].pause();
      index--;
      this.jamz[index].currentTime = 0;
      this.jamz[index].play();
      if (index === 0) {
        this.jamz[index].currentTime = 0;
        this.jamz[index].play();
      }
    };
    
    //add event listeners to the the buttons I pulled earlier.
    playBtn.addEventListener("click", function(event) {
     event.preventDefault();
     jukebox.play();
    })
    
    pauseBtn.addEventListener("click", function(event) {
     event.preventDefault();
     jukebox.pause();
    })
    
    stopBtn.addEventListener("click", function(event) {
     event.preventDefault();
     jukebox.stop();
     })
    
    nextBtn.addEventListener("click", function(event) {
     event.preventDefault();
     jukebox.forward();
     })
    
    backBtn.addEventListener("click", function(event) {
     event.preventDefault();
     jukebox.back();
     })
    
    &#13;
    &#13;
    &#13;

答案 3 :(得分:0)

JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);