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.

alex
  • 479,566
  • 201
  • 878
  • 984
haijin
  • 938
  • 2
  • 11
  • 17
  • OMG! http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – jordanbtucker Nov 12 '10 at 02: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. – aaronasterling Nov 12 '10 at 02: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.. – haijin Nov 13 '10 at 21:34

3 Answers3

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;
alex
  • 479,566
  • 201
  • 878
  • 984
  • 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. – haijin Nov 13 '10 at 21:36
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! :)

nonot1
  • 2,788
  • 4
  • 25
  • 41
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.

Wenxiang Wu
  • 93
  • 1
  • 6
  • 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. – haijin Nov 13 '10 at 21:39