简体   繁体   中英

Python Json extract value in specific format for metrics

I try to add value metrics from json file, the code works, but not in specif file that I want on file.json

with open('file.json') as fp:
     response = json.load(fp)
     for key, item in response.items():
         metric = Metric('duration_sec', 'Requests time taken in seconds', 'summary')
         metric.add_sample('seconds_count', value=item['a'], labels={})
         metric.add_sample('seconds_sum', value=item['b'], labels={})

         yield metric

I want to execute code but with this format code below

file.json

{
  "a": 10,
  "b": 20
}
{
  "a": 11,
  "b": 21
}

it works on:

{
    "0": {
        "a": 10,
        "b": 20
    },
    "1": {
        "a": 11,
        "b": 21
    }
}

As stated in the comments, the requested input file is not valid JSON, so the Python json module will not read it. However, you could do the following:

import re
import ast

with open("file.json", "r") as fp:
    # read in contents
    filedata = fp.read()

    # use re to extract data in dicts
    dictcontent = re.findall(r"\{([^{}]+)\}", filedata)

    # convert into dictionaries
    for content in dictcontent:
        subdict = ast.literal_eval("{" + content + "}")

        metric = Metric('duration_sec', 'Requests time taken in seconds', 'summary')
        metric.add_sample('seconds_count', value=subdict['a'], labels={})
        metric.add_sample('seconds_sum', value=subdict['b'], labels={})

        yield metric

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM