10

I need to map a location in JSON (or JavaScript object) defined by JSON-pointer to the position in JSON text file as {line,column}. Is there any existing JavaScript library that would do it? Writing this code is going to be a bit tedious...

For example, if I have a JSON file (text):

{
  "foo": [
    {
      "bar": 1
    }
  ]
}

then given JSON-pointer /foo/0/bar I need to get {line: 4, column: 7} as the result.

If an equivalent JSON value is stored in this JSON file:

{"foo":[{"bar":1}]}

then the result for the same JSON pointer should be {line: 1, column: 10}.

esp
  • 7,314
  • 6
  • 49
  • 79
  • If it's okay to only handle specifically formatted JSON, you can push the problem back to doing a clone of the JSON, generate some guid, put the guid in that path and stringify, use string searching for the guid – Paul S. Jan 08 '17 at 18:08
  • It won't work, as path can point to a scalar value (like in example) and there is no way to add some UUID to this value. You can add it to a parent object, but I need to map all paths. You can of course replace scalar values with some arrays/objects, but then it would change positions in the original file below (even if it's specifically formatted)... Also, ideally I need mappings to original source files, rather than in specifically formatted JSON. – esp Jan 08 '17 at 18:09
  • 1
    Seems like you will need to write a customer parser/interpreter. Either see if you can build on an existing JSON implementation or start writing your own http://jsbin.com/xixuyiwiwi/edit?js,output – Paul S. Jan 08 '17 at 18:51
  • I've done the opposite task so far: generate mappings while stringifying. https://github.com/epoberezkin/json-source-map – esp Jan 09 '17 at 00:09

1 Answers1

6

This library has the equivalents of JSON.parse/stringify that also return mappings: https://github.com/epoberezkin/json-source-map

esp
  • 7,314
  • 6
  • 49
  • 79