zserge / jsmn

Jsmn is a world fastest JSON parser/tokenizer. This is the official repo replacing the old one at Bitbucket
MIT License
3.65k stars 778 forks source link

Jsmn: value to key #152

Closed embbo closed 5 years ago

embbo commented 5 years ago

is this possible , if i get key by value. I have string on bith sides, "Key" : "value" . i want to search in both direction.

pt300 commented 5 years ago

Yes, it is possible. While traversing objects, instead of looking for specific key, you just check the value instead.

embbo commented 5 years ago

can you give me some idea ? what i have to comepare , i am trying but not get it

pt300 commented 5 years ago

When you have token for your object (it will be the first one for root object) you will want to first check how many children it has (size property). Now you go through the n next tokens which will be keys of the object. Now, as you are on the key you should check if the size property is 1, that means next token will be the value for the key. Otherwise if it's 0 that means the key is without a value and next token will be next key. But if the next token is a value then you just check if it's actually a string by checking type property. of so then you just have to compare the strings. Examples on how to access the string can be found in the repo. Also, be careful in case you have values that are objects/arrays. You will have to skip all tokens which are part of it by basically checking the amount of children for all the children and skipping those tokens.

I hope this lengthy explanation is understandable.

pt300 commented 5 years ago

Some steps can be skipped if you know how exactly the data you are processing looks like and you trust it. For example if it's just an object of key and string values and all keys have values then you could forget about checking sizes of keys and sizes of values. You can skip by two tokens of value doesn't match (skipping key and landing no next value token)