Regex for parsing single key: values out of JSON in Javascript

后端 未结 2 1057
一整个雨季
一整个雨季 2020-11-30 09:07

I\'m trying to see if it\'s possible to lookup individual keys out of a JSON string in Javascript and return it\'s Value with Re

2条回答
  •  爱一瞬间的悲伤
    2020-11-30 09:32

    First, stringify the JSON object. Then, you need to store the starts and lengths of the matched substrings. For example:

    "matched".search("ch") // yields 3
    

    For a JSON string, this works exactly the same (unless you are searching explicitly for commas and curly brackets in which case I'd recommend some prior transform of your JSON object before performing regex (i.e. think :, {, }).

    Next, you need to reconstruct the JSON object. The algorithm I authored does this by detecting JSON syntax by recursively going backwards from the match index. For instance, the pseudo code might look as follows:

    find the next key preceding the match index, call this theKey
    then find the number of all occurrences of this key preceding theKey, call this theNumber
    using the number of occurrences of all keys with same name as theKey up to position of theKey, traverse the object until keys named theKey has been discovered theNumber times
    return this object called parentChain
    

    With this information, it is possible to use regex to filter a JSON object to return the key, the value, and the parent object chain.

    You can see the library and code I authored at http://json.spiritway.co/

提交回复
热议问题