optimal method to parse a json object in a datafile
<p>I am trying to setup a simple data file format, and I am working with these files in Python for analysis.  The format basically consists of header information, followed by the data.  For syntax and future extensibility reasons, I want to use a JSON object for the header information.  An example file looks like this:</p>

<pre><code>{
  "name": "my material",
  "sample-id": null,
  "description": "some material",
  "funit": "MHz",
  "filetype": "material_data"
}
18  6.269311533 0.128658208 0.962033017 0.566268827
18.10945274 6.268810641 0.128691962 0.961950095 0.565591807
18.21890547 6.268312637 0.128725463 0.961814928 0.564998228...
</code></pre>

<p>If the data length/structure is always the same, this is not hard to parse.  However, it brought up in my mind a question about the most flexible way to parse out the JSON object, given an unknown number of lines, and an unknown number of nested curly braces, and potentially more than one JSON object in the file.</p>

<p>If there is only one JSON object in the file, one can use this regular expression:</p>

<pre><code>with open(fname, 'r') as fp:
    fstring = fp.read()

json_string = re.search('{.*}', fstring, flags=re.S)
</code></pre>

<p>However, if there is more than one JSON string, and I want to grab the first one, I need to use something like this:</p>

<pre><code>def grab_json(mystring):
    lbracket = 0
    rbracket = 0
    lbracket_pos = 0
    rbracket_pos = 0

    for i in range(len(mystring)):
        if mystring[i] == '{':
            lbracket = 1
            lbracket_pos = i
            break

    for i in range(lbracket_pos+1, len(mystring)):
        if mystring[i] == '}':
            rbracket += 1
            if rbracket == lbracket:
                rbracket_pos = i
                break
        elif mystring[i] == '{':
            lbracket += 1

    json_string = mystring[lbracket_pos : rbracket_pos + 1]
    return json_string, lbracket_pos, rbracket_pos

json_string, beg_pos, end_pos = grab_json(fstring)
</code></pre>

<p>I guess the question as always: is there a better way to do this?  Better meaning simpler code, more flexible code, more robust code, or really anything?</p>