简体   繁体   English

如何将 json 的值从字符串转换为 javascript 中的 object?

[英]How to convert value of json from string to object in javascript?

I'm using angular 8 and I have a json like this:我正在使用 angular 8 并且我有一个像这样的 json :

     validations: [
    {
      name: "required",
      validator: "Validators.required",
      message: "required"
    }

I dont know How I convert "Validators.required" (string) to Validators.required?我不知道如何将“Validators.required”(字符串)转换为 Validators.required?

I think what you want to do is you that have var Validators = {required: true} as global variable and you want to access it from the string from validations array.我认为你想要做的是你有var Validators = {required: true}作为global变量,你想从validations数组的字符串中访问它。

You can access global var Validators with window.Validators or window["Validators"] .您可以使用window.Validatorswindow["Validators"]访问global var Validators

To access Validators.required you can use window.Validators.required or window["Validators"]["required"] .要访问Validators.required ,您可以使用window.Validators.requiredwindow["Validators"]["required"]

For that you can split "Validators.required" with .为此,您可以将"Validators.required". and use reduce to return window["Validators"]["required"] value as per below code.并根据以下代码使用reduce返回window["Validators"]["required"]值。

 var Validators = { required: true }; let validations = [{ name: "required", validator: "Validators.required", message: "required" }]; let result = validations[0].validator.split('.').reduce((a, i) => a[i], window); // <- Use window to access global variable. console.log(result);


Or if you are having var Validators = {required: true} inside any component then you can use object of that component with second parameter of reduce .或者,如果您在任何component中有var Validators = {required: true} ,那么您可以使用该componentobject和第二个参数reduce

For example you have component object which has Validators = {required: true} then use code like below.例如,您有component object 具有Validators = {required: true}然后使用如下代码。

 let component = { Validators: { required: true } }; let validations = [{ name: "required", validator: "Validators.required", message: "required" }]; let result = validations[0].validator.split('.').reduce((a, i) => a[i], component); console.log(result);

You can use js function JSON.parse()您可以使用js function JSON.parse()

While parsing check for a valid json.解析时检查有效的 json。 By using JSON.parse() in a try catch block通过在 try catch 块中使用JSON.parse()

try { JSON.parse(json); return true; } catch (e) { return false; }}

var object = JSON.parse('validJSON')

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

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