简体   繁体   English

从字符串获取JavaScript对象

[英]Get JavaScript-Object from String

When having: 当有:

var text ='{"parameter":"value"}';

I can use JSON.parse(text); 我可以使用JSON.parse(text); to create a JavaScript Object. 创建一个JavaScript对象。

Problem: I have '{ parameter: "value" }' coming from an axios.default.post request. 问题:我有一个来自axios.default.post请求的'{ parameter: "value" }' JSON.parse throws an error for that. JSON.parse为此引发错误。

So, how can I create an object from that? 那么,如何从中创建对象?

***EDIT***** The response comes from an axios request. ***编辑*****响应来自axios请求。 I debugged it through transformResponse now and in that stage, the data is still{"parameter":"value"}. 我现在通过transformResponse调试了它,在那个阶段,数据仍然是{“ parameter”:“ value”}。 So, Axios creates my problem by - whyever - removing the "; have to figure out, why. 因此,Axios通过-为什么-删除“;”弄清楚了为什么,从而造成了我的问题。

Thanks for your answers, I'll keep you updated. 感谢您的回答,我会及时通知您。

I think you should let api response the correct json valid data. 我认为您应该让api响应正确的json有效数据。 I don't recommand to handle this invalid json string by frontend. 我不建议前端处理此无效的json字符串。


Update: 更新:

According to your issue have you try this config? 根据您的问题,您是否尝试过此配置?

// `transformResponse` allows changes to the response data to be made before
// it is passed to then/catch
transformResponse: [function (data) {
  // Do whatever you want to transform the data
      return data;
}],

Hope this help 希望这个帮助

The problem is with Axios, When receiving JSON from the server, Axios seems to format it to a different format, even though it stays a string when doing "typeof". 问题出在Axios上,当从服务器接收JSON时,Axios似乎将其格式化为另一种格式,即使在执行“ typeof”时仍保留字符串。

My solution was to add responseType="text" to the config for the request. 我的解决方案是将responseType =“ text”添加到请求的配置中。 This way, I receive a text, that I can parse with JSON.parse. 这样,我收到一个文本,可以使用JSON.parse进行解析。

However, this is somehow not perfect, as Axios provides JSON formating, so, if anyone has an answer to "How can I use the Axios formated Result", I'ld be happy to know about it. 但是,由于Axios提供JSON格式,所以这在某种程度上并不完美,因此,如果有人对“如何使用Axios格式的结果”有答案,我将很高兴知道这一点。

'{ parameter: "value"}' is not JSON as you've probably figured out as the key isn't wrapped in quotes. '{ parameter: "value"}'不是JSON,因为您可能已经发现,因为密钥没有用引号引起来。 There is a trick that you can use to turn a javascript object string back into an object. 您可以使用一个技巧将javascript对象字符串变回对象。

As @ASDFGerte noted this is not a safe method if you are not sure of your string's source. 正如@ASDFGerte指出的那样,如果您不确定字符串的来源,则这不是安全的方法。

 function parse(str) { return Function('"use strict";return (' + str + ')')(); } const obj = parse('{ parameter: "value"}'); console.log(obj); 

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

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