Convert string to JSON Object

前端 未结 7 1576
梦如初夏
梦如初夏 2020-12-09 01:57

How do I convert string to object? I am facing this problem because I am trying to read the elements in the JSON string using \"each\".

My string is given below.

相关标签:
7条回答
  • 2020-12-09 02:33

    Your string is not valid. Double quots cannot be inside double quotes. You should escape them:

    "{\"TeamList\" : [{\"teamid\" : \"1\",\"teamname\" : \"Barcelona\"}]}"
    

    or use single quotes and double quotes

    '{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}'
    
    0 讨论(0)
  • 2020-12-09 02:34

    only with js

       JSON.parse(jsonObj);
    

    reference

    0 讨论(0)
  • 2020-12-09 02:38

    Enclose the string in single quote it should work. Try this.

    var jsonObj = '{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}';
    var obj = $.parseJSON(jsonObj);
    

    Demo

    0 讨论(0)
  • 2020-12-09 02:42

    try:

    var myjson = '{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}';
    var newJ= $.parseJSON(myjson);
        alert(newJ.TeamList[0].teamname);
    
    0 讨论(0)
  • 2020-12-09 02:46

    Quick answer, this eval work:

    eval('var obj = {"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}')
    
    0 讨论(0)
  • 2020-12-09 02:46

    Without eval:

    Your original string was not an actual string.

    jsonObj = "{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}"
    

    The easiest way to to wrap it all with a single quote.

     jsonObj = '"{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}"'
    

    Then you can combine two steps to parse it to JSON:

     $.parseJSON(jsonObj.slice(1,-1))
    
    0 讨论(0)
提交回复
热议问题