简体   繁体   中英

Parsing non-JSON JavaScript object with Jackson

How can Jackson be made to parse the following JavaScript object?

{
  // this is a comment
  x: '1',
  y: {
    z: '2'
  }
}

Note that the example object above is not actual JSON—it is a JavaScript object which (1) doesn't have quotes around attribute names, (2) uses single, not double, quotes around values, and (3) contains a comment.

Use case: I need to parse a JavaScript object that is embedded in HTML. I can get the JavaScript object itself, but I now need to parse it.

You can try with some parser options :

private static final ObjectMapper om = new ObjectMapper();
om.configure(JsonGenerator.Feature.ALLOW_SINGLE_QUOTES, true);
om.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
om.configure(JsonParser.Feature.ALLOW_COMMENTS, true);

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