简体   繁体   English

最佳实践 - JSON 与 JS 对象

[英]Best practice - JSON vs JS Object

Consider this simple angular example & navigate to question.service.ts考虑这个简单的角度示例并导航到question.service.ts

Snippet from question.service.ts:来自 question.service.ts 的片段:

new DropdownQuestion({
        key: 'brave',
        label: 'Bravery Rating',
        options: [
          {key: 'solid',  value: 'Solid'},
          {key: 'great',  value: 'Great'},
          {key: 'good',   value: 'Good'},
          {key: 'unproven', value: 'Unproven'}
        ],
        order: 3
      })

Alternate to above (raw json):替代上述(原始 json):

{
       key: 'brave',
        label: 'Bravery Rating',
        options: [
          {key: 'solid',  value: 'Solid'},
          {key: 'great',  value: 'Great'},
          {key: 'good',   value: 'Good'},
          {key: 'unproven', value: 'Unproven'}
        ],
        order: 3
      }

What I feel is rather than passing this raw json (as described above), I use the method 1 described above.我觉得不是传递这个原始json(如上所述),而是使用上述方法1。

I don't have enough arguments to support my point here.我没有足够的论据来支持我的观点。 But I feel that passing in JS object using the supplied JSON object as parameter is way better than passing raw json, in terms or readability, maintainability & OOP.但我觉得使用提供的 JSON 对象作为参数传入 JS 对象比传递原始 json 好得多,无论是在可读性、可维护性和 OOP 方面。

I am facing a hard time convincing my fellow colleagues to agree with my approach.我很难说服我的同事同意我的方法。 What would actually be the best way here?实际上,这里最好的方法是什么? Is passing raw json really a better approach then JS?传递原始 json 真的是比 JS 更好的方法吗? or vice versa?或相反亦然? Is there any alternate way to this?有什么替代方法吗?

Thank you in advance.先感谢您。

  • First of all, both of them are completely irrelevant since first option expecting some specific format as input however second option is free data structure which can be feed as input to DropdownQuestion .首先,它们两者完全无关,因为第一个选项需要一些特定的格式作为input但是第二个选项是免费的数据结构,可以作为DropdownQuestion input

  • Second, I am guessing, what you are seeking for is to force the control to have very specific structure rather than wrapping something in it.其次,我猜测,您要寻找的是强制控件具有非常特定的结构,而不是在其中包装某些东西。 You DropdownQuestion class should be look like as -DropdownQuestion类应该看起来像 -

     class DropdownQuestion implements Control{ public key; public label; public order; public options =[]; }

Here Control is common interface that needs to be implemented by all Controls .这里Control是所有Controls都需要实现的通用接口。

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

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