ofproto: Remove dummy 'in_port' variable.
[openvswitch] / python / ovs / json.py
index 1e26a62909240903acd476a61764f01782c49034..96f3cffc856b5fb8643a4ee0638a33e19becb370 100644 (file)
@@ -1,4 +1,4 @@
-# Copyright (c) 2010 Nicira Networks
+# Copyright (c) 2010, 2011 Nicira Networks
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
@@ -28,15 +28,7 @@ for i in range(32):
         escapes[i] = u"\\u%04x" % i
 
 def __dump_string(stream, s):
-    stream.write(u"\"")
-    for c in s:
-        x = ord(c)
-        escape = escapes.get(x)
-        if escape:
-            stream.write(escape)
-        else:
-            stream.write(c)
-    stream.write(u"\"")
+    stream.write(u'"%s"' % ''.join(escapes.get(ord(c), c) for c in s))
 
 def to_stream(obj, stream, pretty=False, sort_keys=True):
     if obj is None:
@@ -59,26 +51,22 @@ def to_stream(obj, stream, pretty=False, sort_keys=True):
             items = sorted(obj.items())
         else:
             items = obj.iteritems()
-        i = 0
-        for key, value in items:
+        for i, (key, value) in enumerate(items):
             if i > 0:
                 stream.write(u",")
-            i += 1
             __dump_string(stream, unicode(key))
             stream.write(u":")
             to_stream(value, stream, pretty, sort_keys)
         stream.write(u"}")
     elif type(obj) in (list, tuple):
         stream.write(u"[")
-        i = 0
-        for value in obj:
+        for i, value in enumerate(obj):
             if i > 0:
                 stream.write(u",")
-            i += 1
             to_stream(value, stream, pretty, sort_keys)
         stream.write(u"]")
     else:
-        raise Error("can't serialize %s as JSON" % obj)
+        raise Exception("can't serialize %s as JSON" % obj)
 
 def to_file(obj, name, pretty=False, sort_keys=True):
     stream = open(name, "w")
@@ -113,10 +101,9 @@ def from_string(s):
     try:
         s = unicode(s, 'utf-8')
     except UnicodeDecodeError, e:
-        seq = ' '.join(["0x%2x" % ord(c) for c in e.object[e.start:e.end]])
-        raise Error("\"%s\" is not a valid UTF-8 string: "
-                    "invalid UTF-8 sequence %s" % (s, seq),
-                    tag="constraint violation")
+        seq = ' '.join(["0x%2x" % ord(c)
+                        for c in e.object[e.start:e.end] if ord(c) >= 0x80])
+        return ("not a valid UTF-8 string: invalid UTF-8 sequence %s" % seq)
     p = Parser(check_trailer=True)
     p.feed(s)
     return p.finish()