简体   繁体   English

在JavaScript中将类似JSON的文件类型解析为JSON

[英]Parsing JSON-like file type to JSON in JavaScript

I have lots of files with an unusual file extension. 我有很多文件带有不寻常的文件扩展名。

I need to read the files using JavaScript and convert their contents to JSON or regular JavaScript objects. 我需要使用JavaScript读取文件,并将其内容转换为JSON或常规JavaScript对象。

Is this even possible? 这有可能吗?

I have some hope, because the files are already structured very similar to JSON: 我有一些希望,因为文件的结构已经非常类似于JSON:

// file.unusualFileType

Page: {
  id: P001
  Title: "Page Title"
  URL: "/home"
  Elements: {
    Button: {
      Text: "Click me"
      Action: SAVE
    }
  }
}

EDIT: Håken Lid kindly provided a solution for my particular use case. 编辑:HåkenLid为我的特定用例提供了一个解决方案。 Out of curiosity I would still be interested in how to read any file as a string with JavaScript and how one could possible parse such a string. 出于好奇,我仍然会对如何使用JavaScript将任何文件读取为字符串以及如何解析这样的字符串感兴趣。

It would be valid yaml if you strip out the curly brackets. 如果您将花括号去掉,它将是有效的Yaml。 You can use js-yaml to parse the sample data, so maybe it works with the rest of your files too? 您可以使用js-yaml来解析示例数据,所以也许它也可以与其余文件一起使用?

 const rawData = ` Page: { id: P001 Title: "Page Title" URL: "/home" Elements: { Button: { Text: "Click me" Action: SAVE } } }` const yamlData = rawData.replace(/[{}]/g, '') console.log(jsyaml.load(yamlData)) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/js-yaml/3.13.1/js-yaml.min.js"></script> 

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

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