1

I have the following JSON string as part of a log line.

cells : {"Lac":"7824","CntryISO":"us","NetTyp":"GSM","NetOp":"310260","Cid":"11983"}

I want to filter out to the following format: {"Lac":"7824","Cid":"11983"}.

How can do this using regular expression ? in Javascript or Python ? the keys are constant strings(Lac, CntryISO, ...), but the value strings are varying.

3
  • OMG! stackoverflow.com/questions/1732348/… Commented Nov 12, 2010 at 2:18
  • except that using regexen to parse JSON is even more retarded than using them to parse XML because JSON is so much easier to work with correctly. Commented Nov 12, 2010 at 2:46
  • For those who think this is retarded question...This is from the log text I got from the server...I know I can easily re-construct the json object and manipulate it...however, it is just too much overhead to create a json for each log line for this....I believe reg exp should be able to handle it.. Commented Nov 13, 2010 at 21:34

3 Answers 3

5

Why don't you just delete them in JavaScript?

var myJson = {"Lac":"7824","CntryISO":"us","NetTyp":"GSM","NetOp":"310260","Cid":"11983"};

delete myJson.Lac;
delete myJson.cId;
Sign up to request clarification or add additional context in comments.

1 Comment

why can't reg exp handle this ? it should not be that hard...I hate to create a json object for each log line and let GC run constantly.
1

To expand and explain @alex answer:

JSON is a nested multi dimensional structure. Simply filtering the "string-ifiyed form of a Javascript object" (aka JSON) will work in very simple cases, but will rapidly fail when the structure is no longer flat or it starts to get complex with escaped fields, etc.

At that point you will need proper parsing logic. This is nicely supplied by Javascript itself, to quote @alexes code:

var myJson = {"Lac":"7824","CntryISO":"us","NetTyp":"GSM","NetOp":"310260","Cid":"11983"};

delete myJson.Lac;
delete myJson.cId;

Or, if you want to use python, the json module will work just fine: http://docs.python.org/library/json.html

Good luck! :)

Comments

0

Why would you want to use regex for this when you can just use a JSON parser/serializer? Try cjson in Python if you are concerned about speed, it is faster than 'json' module in the Python standard library.

1 Comment

I can...but entail the overhead of creating json object for each log line...I am just wondering this should not be hard with reg exp...maybe I am wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.