开发者

regular expression to filter out part of key value in a json string

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开发者_Python百科":"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.


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;


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! :)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜