MCPcopy
hub / github.com/OS-Copilot/OS-Copilot / extract_json_from_string

Method extract_json_from_string

oscopilot/modules/base_module.py:38–70  ·  view source on GitHub ↗

Identifies and extracts JSON data embedded within a given string. This method searches for JSON data within a string, specifically looking for JSON blocks that are marked with ```json``` notation. It attempts to parse and return the first JSON object found.

(self, text)

Source from the content-addressed store, hash-verified

36 return result
37
38 def extract_json_from_string(self, text):
39 """
40 Identifies and extracts JSON data embedded within a given string.
41
42 This method searches for JSON data within a string, specifically looking for
43 JSON blocks that are marked with ```json``` notation. It attempts to parse
44 and return the first JSON object found.
45
46 Args:
47 text (str): The text containing the JSON data to be extracted.
48
49 Returns:
50 dict: The parsed JSON data as a dictionary if successful.
51 str: An error message indicating a parsing error or that no JSON data was found.
52 """
53 # Improved regular expression to find JSON data within a string
54 json_regex = r'```json\s*\n\{[\s\S]*?\n\}\s*```'
55
56 # Search for JSON data in the text
57 matches = re.findall(json_regex, text)
58
59 # Extract and parse the JSON data if found
60 if matches:
61 # Removing the ```json and ``` from the match to parse it as JSON
62 json_data = matches[0].replace('```json', '').replace('```', '').strip()
63 try:
64 # Parse the JSON data
65 parsed_json = json.loads(json_data)
66 return parsed_json
67 except json.JSONDecodeError as e:
68 return f"Error parsing JSON data: {e}"
69 else:
70 return "No JSON data found in the string."

Callers 5

decompose_taskMethod · 0.80
replan_taskMethod · 0.80
judge_toolMethod · 0.80
analysis_toolMethod · 0.80
design_courseMethod · 0.80

Calls

no outgoing calls

Tested by

no test coverage detected