2017-02-15 49 views
0

我有一個字符串對象類似如下:轉換幾乎JSON字符串JSON對象中的JavaScript

CustomData { 
    href: 'https://api.stormpath.com/v1/accounts/fdsq/customData', 
    createdAt: '2017-02-12T21:06:34.086Z', 
    modifiedAt: '2017-02-14T20:36:45.879Z', 
    ethereum_contract_address: '485dsq41g52fdsqqds', 
    ethereum_provider: 'proqxy53fdsq.yoicsfdsqfdsq.net:31gky6736' } 

我想這個字符串轉換成JSON對象,然後我就可以使用正常。但我似乎無法將其轉換爲一個簡單的字符串,然後我可以使用substring,然後解析爲JSON。

這裏是我曾嘗試:

var rawString = req.user.customData; 
console.log(rawString); 
var stringJson = String(rawString).substring(0, 11); 
console.log(stringJson.toString()); 
var customData = JSON.parse(stringJson); 
console.log(customData); 

我不幸坐上JSON.parse stcuk,好像串字符串(rawString)實際上並沒有將其轉換爲一個字符串,但只retruns [對象目的]。

+3

如果它不是JSON,那不是JSON,如果你打算用'JSON.parse'解析字符串,它**有**是有效的JSON,雙引號和全部。 – adeneo

回答

2

您應該使用

JSON.stringify(jsonData); 

然後只是簡單的解析

JSON.parse(jsonString) 
+0

不錯的答案,但是,它沒有給出解釋。因爲他/她感到困惑,所以需要解釋。 –

+0

就這麼簡單。 JSON.stringify將數據轉換爲字符串。 JSON.parse將JSON格式的字符串轉換爲可讀的JSON – Merigold

0

你需要JSON.stringigy(obj);,讓您的數據的JSON對象。繼承人的代碼:

var customData = { 
 
    href: 'https://api.stormpath.com/v1/accounts/fdsq/customData', 
 
    createdAt: '2017-02-12T21:06:34.086Z', 
 
    modifiedAt: '2017-02-14T20:36:45.879Z', 
 
    ethereum_contract_address: '485dsq41g52fdsqqds', 
 
    ethereum_provider: 'proqxy53fdsq.yoicsfdsqfdsq.net:31gky6736' 
 
} 
 
console.log(customData); 
 
var stringJson = JSON.stringify(customData); 
 
console.log(stringJson); 
 
var customData = JSON.parse(stringJson); 
 
console.log(customData);

0
的CustomData

是JSON:它包含鍵和值。 JSON代表JavaScript Object Notation。您將JSON與JSON字符串混淆。從前者可以實現通過

var JSONString = JSON.stringify(CustomData); 

後者可以通過

JSON.parse(JSONString); 

解析它然而,由於你的對象已經是一個JSON,你應該能夠正確地使用它,知道是什麼意思在你的場景中。