2017-07-25 27 views
1

我有一個簡單的函數來將選定的對象ID發佈到會話存儲中,它可以很好地處理數字,但是當我將其更改爲某個單詞時,它無效,任何想法爲什麼以及如何解決它?將對象ID傳遞給會話存儲

我認爲這將是罰款,因爲他們都是一個字符串,你可以看到我的功能在底部解析JSON,我不明白爲什麼它只適用於數字?

代碼

$scope.productsandformats = [{ 
    "name": "name 1", 
    "format": [{ 
     "Fname": "test (ROADSIDE TEMP)", 
     "id": "Roadside" 
    }, { 
     "Fname": "test Sheet", 
     "id": "2" 
    }, { 
     "Fname": "Wrap test (Digital)", 
     "id": "3" 
    }] 
}, { 
    "name": "name 2, 
    "format": [{ 
     "Fname": "2 test", 
     "id": "4" 
    }, { 
     "Fname": "test Live (Digital)", 
     "id": "5" 
    }] 
}; 
$scope.productTypeChange = function() { 
    $scope.formats = $scope.productsandformats.find(ps => ps.name === $scope.formData.ProductType.name) 
     //NG-Change 
    $scope.myFunc = function() { 
     var jsonItem = JSON.parse($scope.formData.formatType.id); 
     sessionStorage.setItem('format', jsonItem); 
    } 
} 
}); 

我得到一個錯誤檢查

SyntaxError: Unexpected token R in JSON at position 0 at JSON.parse()

+2

檢查「JSON.parse」的輸入是否爲有效的JSON。另外你的代碼示例在'name 2'後面缺少一個''' – Halcyon

回答

0

下面的JSON你正在分析該ID不JSON,這是wh你得到錯誤。

事實上,整個範圍對象只是一個JavaScript對象,而不是JSON(它是一種文本格式)。

你得到的Id是字符串「Roadside」,但是如果它是JSON字符串,它會看起來像「{\」key \「:\」value \「}」。它缺少大括號的事實告訴解析器它是錯誤的。

+0

好的,謝謝你的信息 – Beep

0

嘗試$scope

$scope.productsandformats =[{ 
    "name": "name 1", 
    "format": [{ 
     "Fname": "test (ROADSIDE TEMP)", 
     "id": "Roadside" 
    }, { 
     "Fname": "test Sheet", 
     "id": "2" 
    }, { 
     "Fname": "Wrap test (Digital)", 
     "id": "3" 
    }] 
}, { 
    "name": "name 2", 
    "format": [{ 
     "Fname": "2 test", 
     "id": "4" 
    }, { 
     "Fname": "test Live (Digital)", 
     "id": "5" 
    }] 
}]