简体   繁体   English

将几乎JSON字符串转换为JSON对象Javascript

[英]Convert almost JSON string to JSON object Javascript

I have an string object like the following: 我有一个类似于以下的字符串对象:

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' }

I am trying to convert this string to a JSON object that I can then use properly. 我正在尝试将此字符串转换为可以正确使用的JSON对象。 But i can't seem to convert this to a simple string that I could then substring and then parse to JSON. 但是我似乎无法将其转换为一个简单的字符串,然后可以将该子字符串转换为JSON。

Here is what i have attempted: 这是我尝试过的:

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);

I unfortunatly get stcuk on the JSON.parse, it seems like the string String(rawString) does not actually convert it to a string but only retruns [object Object]. 不幸的是,我在JSON.parse上获得了stcuk,似乎字符串String(rawString)实际上并未将其转换为字符串,而只是重新运行了[object Object]。

You should use 你应该用

JSON.stringify(jsonData);

then just simply parse 然后只需解析

JSON.parse(jsonString)

You need JSON.stringigy(obj); 您需要JSON.stringigy(obj); to get a JSON-object of your data. 获取数据的JSON对象。 Heres the code: 这是代码:

 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); 

CustomData is a JSON: It contains keys and values. CustomData是JSON:它包含键和值。 JSON stands for JavaScript Object Notation . JSON代表JavaScript Object Notation You confuse JSON with JSON string. 您将JSON与JSON字符串混淆。 From the former you can achieve the latter via 在前者中,您可以通过

var JSONString = JSON.stringify(CustomData);

You can parse it via 您可以通过解析

JSON.parse(JSONString);

However, since your object is already a JSON, you should be able to use it properly, whatever that means in your scenario. 但是,由于您的对象已经是JSON,因此无论您的情况如何,都应该能够正确使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM