简体   繁体   中英

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.

Is this even possible?

I have some hope, because the files are already structured very similar to 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. 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.

It would be valid yaml if you strip out the curly brackets. You can use js-yaml to parse the sample data, so maybe it works with the rest of your files too?

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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