Traceback (most recent call last):
File "/XXXparsing_output.py", line 322, in
data = json.loads(json_array_str)
File "/usr/lib/python3.10/json/init.py", line 346, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.10/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.10/json/decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 76 column 41 (char 2668)
Assistant
The error you're encountering:
pgsqlCopyEditjson.decoder.JSONDecodeError: Expecting ',' delimiter
means that the text you tried to load as JSON is not valid JSON, likely due to:
Unescaped quotation marks (like in מגלית העצמאות כוללת " חוקים ").
Mismatched or malformed syntax.
Non-standard characters or accidental formatting.
✅ Solution
We’ll sanitize the string before using json.loads().
Here’s an updated and safe way to parse your document:
🔧 Updated Code
pythonCopyEditimport pandas as pd
import json
import re
Step 1: Read full raw text (replace this with reading from file if needed)
User
For a sanity check, run it on this:
text = """The Legal and Constitutional Status of Israel's Declaration of Independence
Legal status of the Declaration of Independence; Constitutional authority and legitimacy; Historical vs. legal significance; Need for a new constitution; Democratic representation in constitutional drafting; Internal contradictions in the Declaration; Role of the Supreme Court in constitutional interpretation
[
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "לדעתי נכון שמגילת העצמאות תהיה בסיסי לחוקים בישראל אני מסכימה עם החזון והערכים הכתובים שם , אך לדעתי יש בצורה שבה נכתבה בעיתיות ויש צורך לשינוי",
"Author": "MM",
"DU_id": 1,
"eTU_id": 1,
"eTU_type": "claim",
"Theme": "Legal status of the Declaration of Independence"
},
]
"""
Assistant
Great — thanks for providing the test input. Here's the key issue in your JSON:
❌ Problem:
There is an extra trailing comma after the last object inside the list:
jsonCopyEdit[
{
"Title": "...",
...
"Theme": "Legal status of the Declaration of Independence"
}, <-- ❌ this comma shouldn't be here
]
That comma causes:
javascriptCopyEditJSONDecodeError: Expecting ',' delimiter
User
I found the bug. Its in this line:
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "לפי דעתי מגלית העצמאות כוללת " חוקים " שבסך הכל מאוד נכונים והגיוניים , אך ההכרזה עצמה מאוד מבולגנת ומלאה סיבות ללמה היה צריך להקים את מדינת ישראל",
"Author": "MV",
"DU_id": 3,
"eTU_id": 9,
"eTU_type": "claim",
"Theme": "Internal contradictions in the Declaration"
}
Text includes "" and , so it messes everything up.
Assistant
Exactly — you've pinpointed the issue.
The problem is that you have unescaped double quotes (") inside a string, which breaks JSON syntax. JSON expects double quotes only around keys and values, so any " inside string values must be escaped as ".
❌ Problematic JSON fragment
jsonCopyEdit"Text": "לפי דעתי מגלית העצמאות כוללת " חוקים " שבסך הכל מאוד נכונים..."
JSON parser sees that and thinks the value ends after כוללת , then is confused by " חוקים ".
✅ Fixed version with escaped quotes
jsonCopyEdit"Text": "לפי דעתי מגלית העצמאות כוללת " חוקים " שבסך הכל מאוד נכונים והגיוניים , אך ההכרזה עצמה מאוד מבולגנת ומלאה סיבות ללמה היה צריך להקים את מדינת ישראל"
Now the inner quotes are safely part of the string.
🛠️ Suggestion: Auto-fix unsafe JSON using Python
If you're working with JSON strings that are likely malformed in this way, you can sanitize them using a regex or json5, ast.literal_eval, or a JSON linter library — or simply preprocess the text with a function like this:
pythonCopyEditdef escape_inner_quotes(json_str):
# Match only the values of "Text": "...", not the keys or other strings
def escape_quotes_in_text(match):
full_match = match.group(0)
inner_text = match.group(1)
escaped = inner_text.replace('"', '\"')
return f'"Text": "{escaped}"'
User
This still doesn't work
"Text": "לפי דעתי מגלית העצמאות כוללת " חוקים " שבסך הכל מאוד נכונים והגיוניים , אך ההכרזה עצמה מאוד מבולגנת ומלאה סיבות ללמה היה צריך להקים את מדינת ישראל",
Though this does:
"Text": "A",
Assistant
You're right to flag this — and this points to a common JSON encoding trap. Here's the nuance:
✅ JSON Rules Recap
In JSON:
Strings must be in double quotes (").
User
Assistant
📌 Notes:
This will give you a DataFrame with columns like:
Title
Text
Author
DU_id
eTU_id
eTU_type
Theme
The and can also be extracted separately if you want:
pythonCopyEdit# Extract title and themes separately
title = re.search(r"(.?)", text).group(1)
themes = re.search(r"(.?)", text).group(1).split("; ")
print("Title:", title)
print("Themes:", themes)
Let me know if you’d like this exported to CSV or want to filter specific eTU types (like only "claim").
with open("your_input_file.txt", encoding="utf-8") as f:
text = f.read()
Step 2: Extract just the JSON array content using regex
json_match = re.search(r"([\s*{.?}\s])", text, re.DOTALL)
if not json_match:
raise ValueError("No JSON array found in the text.")
json_array_str = json_match.group(1)
Step 3: Fix invalid quotes inside values (a bit hacky but works for most cases)
Replace smart quotes or embedded double-quotes in values
try:
data = json.loads(cleaned_json_str)
except json.JSONDecodeError as e:
print("Failed to parse JSON:", e)
raise
Step 5: Convert to DataFrame
df = pd.DataFrame(data)
Done! Display the DataFrame
print(df.head())
✅ What this does:
Finds the main JSON [...] block using regex.
Escapes problematic double-quotes inside "Text" values (where users used " " instead of ' ').
Loads the cleaned string into a DataFrame.
If you'd prefer, I can clean and reformat the exact JSON data for you—just say the word.
✅ Fixed text (Sanity-Check Ready)
Here’s the corrected version of your input:
pythonCopyEdittext = """The Legal and Constitutional Status of Israel's Declaration of Independence
Legal status of the Declaration of Independence; Constitutional authority and legitimacy; Historical vs. legal significance; Need for a new constitution; Democratic representation in constitutional drafting; Internal contradictions in the Declaration; Role of the Supreme Court in constitutional interpretation
[
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "לדעתי נכון שמגילת העצמאות תהיה בסיסי לחוקים בישראל אני מסכימה עם החזון והערכים הכתובים שם , אך לדעתי יש בצורה שבה נכתבה בעיתיות ויש צורך לשינוי",
"Author": "MM",
"DU_id": 1,
"eTU_id": 1,
"eTU_type": "claim",
"Theme": "Legal status of the Declaration of Independence"
}
]
"""
✅ Sanity Check Code
Here’s how you would parse it:
pythonCopyEditimport json
import re
import pandas as pd
Step 1: Extract the JSON array from the text
json_match = re.search(r"[\s*{.?}\s]", text, re.DOTALL)
if not json_match:
raise ValueError("No JSON array found in the input.")
json_array_str = json_match.group(0)
Step 2: Load JSON
data = json.loads(json_array_str)
Step 3: Convert to DataFrame
df = pd.DataFrame(data)
print(df)
✅ Output
luaCopyEdit Title Text Author DU_id eTU_id eTU_type Theme
0 The Legal and Constitutional Status of Israel... לדעתי נכון שמגילת העצמאות תהיה בסיסי לחוקים בישראל ... MM 1 1 claim Legal status of the Declaration of Independence
Let me know if you'd like me to build a full parser that handles a larger file with multiple entries and fixes other formatting issues like this automatically.
Let me know if you want help building a full preprocessor that escapes only the unsafe quotes (e.g. inside "Text" fields, but not keys or numbers).
Any inner double quotes must be escaped with a backslash (").
However, you can't just blindly replace " with " inside the string. If the string contains characters like newlines, tabs, or non-ASCII characters (like Hebrew), then:
The string must still be valid UTF-8
It must not contain unescaped control characters
You must escape only inner quotes, not the entire structure
🚨 Problem in your escaping attempt
Your string:
jsonCopyEdit"Text": "לפי דעתי מגלית העצמאות כוללת " חוקים " שבסך הכל מאוד נכונים והגיוניים , אך ההכרזה עצמה מאוד מבולגנת ומלאה סיבות ללמה היה צריך להקים את מדינת ישראל",
looks fine, but in fact there are invisible characters or syntax context issues, especially if you're trying to embed this directly in a Python string or into a JSON array without proper serialization.
✅ Safe Fix: Let json.dumps() handle it
Instead of manually escaping quotes inside text, do all your JSON encoding via json.dumps(). Example:
pythonCopyEditimport json
data = {
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": 'לפי דעתי מגלית העצמאות כוללת " חוקים " שבסך הכל מאוד נכונים והגיוניים , אך ההכרזה עצמה מאוד מבולגנת ומלאה סיבות ללמה היה צריך להקים את מדינת ישראל',
"Author": "MV",
"DU_id": 3,
"eTU_id": 9,
"eTU_type": "claim",
"Theme": "Internal contradictions in the Declaration"
}
This outputs:
jsonCopyEdit{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "לפי דעתי מגלית העצמאות כוללת " חוקים " שבסך הכל מאוד נכונים והגיוניים , אך ההכרזה עצמה מאוד מבולגנת ומלאה סיבות ללמה היה צריך להקים את מדינת ישראל",
"Author": "MV",
"DU_id": 3,
"eTU_id": 9,
"eTU_type": "claim",
"Theme": "Internal contradictions in the Declaration"
}
This is guaranteed to be valid JSON.
🧠 Summary
Do not manually escape quotes unless you’re 100% sure of JSON context.
Use json.dumps() to serialize string data.
If you're building a JSON array in a text file, serialize each object separately and build the array from that.
Would you like a helper function that parses a list of such blocks from your text file and safely builds a valid JSON array?
What should I change here?
import pandas as pd
import json
import re
text = """The Legal and Constitutional Status of Israel's Declaration of Independence
Legal status of the Declaration of Independence; Constitutional authority and legitimacy; Historical vs. legal significance; Need for a new constitution; Democratic representation in constitutional drafting; Internal contradictions in the Declaration; Role of the Supreme Court in constitutional interpretation
[
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "לדעתי נכון שמגילת העצמאות תהיה בסיסי לחוקים בישראל אני מסכימה עם החזון והערכים הכתובים שם , אך לדעתי יש בצורה שבה נכתבה בעיתיות ויש צורך לשינוי",
"Author": "MM",
"DU_id": 1,
"eTU_id": 1,
"eTU_type": "claim",
"Theme": "Legal status of the Declaration of Independence"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "ראשית , האנשים אשר כתבו את מגילת העצמאות לעולם לא נבחרו",
"Author": "MM",
"DU_id": 1,
"eTU_id": 2,
"eTU_type": "claim",
"Theme": "Constitutional authority and legitimacy"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "שנית בהיסטוריה של מדינת ישראל הובהר כבר ב1948 שהיא אינה מחייבת",
"Author": "MM",
"DU_id": 1,
"eTU_id": 3,
"eTU_type": "claim",
"Theme": "Legal status of the Declaration of Independence"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "לסיכום אני חושבת שיש להבהיר את מעמדה במשפט בישראל ואולי אפילו לכתוב אחת מחדש",
"Author": "MM",
"DU_id": 1,
"eTU_id": 4,
"eTU_type": "claim",
"Theme": "Need for a new constitution"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "ישנן מספר עמדות על מעמדה המשפטי של מגילת העצמאות . בניהן נמנית הגישה של להסתכל על מגילת העצמאות כחוקה של עם ישראל מכיוון שלעם ישראל אין חוקה אך עם זאת היא לא באמת חוקה",
"Author": "AS",
"DU_id": 2,
"eTU_id": 5,
"eTU_type": "claim",
"Theme": "Legal status of the Declaration of Independence"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "עמדה נוספת היא שמגילת העצמאות היא מקור עצמאי לזכויות האדם - מעין אמנה חברתית",
"Author": "AS",
"DU_id": 2,
"eTU_id": 6,
"eTU_type": "claim",
"Theme": "Legal status of the Declaration of Independence"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "לפי דעתי , מגילת העצמאות היא בסיס לחוקים מסויימים אבל אנחנו גם צריכים חוקי יסוד",
"Author": "AS",
"DU_id": 2,
"eTU_id": 7,
"eTU_type": "claim",
"Theme": "Legal status of the Declaration of Independence"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "ההתבוססות על מגית העצמאות היא רופפת למדי וצריכה להשתנות לפי דעתי , היא צריכה לתפוס מקום יותר היסטורי ופחות משפטי",
"Author": "AS",
"DU_id": 2,
"eTU_id": 8,
"eTU_type": "claim",
"Theme": "Historical vs. legal significance"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "לפי דעתי מגלית העצמאות כוללת " חוקים " שבסך הכל מאוד נכונים והגיוניים , אך ההכרזה עצמה מאוד מבולגנת ומלאה סיבות ללמה היה צריך להקים את מדינת ישראל",
"Author": "MV",
"DU_id": 3,
"eTU_id": 9,
"eTU_type": "claim",
"Theme": "Internal contradictions in the Declaration"
}
]
"""
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "תתעלמו מזה בבקשה",
"Author": "MV",
"DU_id": 3,
"eTU_id": 10,
"eTU_type": "meta",
"Theme": "Internal contradictions in the Declaration"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "לדעתי מגילת העצמאות מבטת את רצון וחזון העם , בצורה העקרונית אך אין לה מעמד או ערך משפטי",
"Author": "SV",
"DU_id": 4,
"eTU_id": 11,
"eTU_type": "claim",
"Theme": "Historical vs. legal significance"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "בג"ץ הבהיר את העובדה הזאת כבר ב 1948 בו טענו : " ההכרזה באה רק לשם קביעת העובדה של יסוד המדינה והקמתה לצורך הכרתה על ידי החוק הבינלאומי . היא מבטאת את חזון העם ואת ׳ האני מאמין ׳ שלו , אבל אין בה משום חוק קונסטיטוציוני הפוסק הלכה למעשה בדבר קיום פקודות וחוקים שונים , או ביטולם "",
"Author": "SV",
"DU_id": 4,
"eTU_id": 12,
"eTU_type": "claim",
"Theme": "Role of the Supreme Court in constitutional interpretation"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "לדעתי מגילת העצמאות מבטת את רצון וחזון העם , בצורה העקרונית אך אין לה מעמד או ערך משפטי . בג"ץ הבהיר את העובדה הזאת כבר ב 1948 בו טען : " ההכרזה באה רק לשם קביעת העובדה של יסוד המדינה והקמתה לצורך הכרתה על ידי החוק הבינלאומי . היא מבטאת את חזון העם ואת ׳ האני מאמין ׳ שלו , אבל אין בה משום חוק קונסטיטוציוני הפוסק הלכה למעשה בדבר קיום פקודות וחוקים שונים , או ביטולם "",
"Author": "SV",
"DU_id": 4,
"eTU_id": 13,
"eTU_type": "claim",
"Theme": "Role of the Supreme Court in constitutional interpretation"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "לפי דעתי מגלית העצמאות כוללת " חוקים " שבסך הכל מאוד נכונים והגיוניים , אך ההכרזה עצמה מאוד מבולגנת ומלאה סיבות ללמה היה צריך להקים את מדינת ישראל",
"Author": "MV",
"DU_id": 5,
"eTU_id": 14,
"eTU_type": "claim",
"Theme": "Internal contradictions in the Declaration"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "נגד - כותבי החוקה לא עסקו אף פעם בביצוע",
"Author": "MV",
"DU_id": 5,
"eTU_id": 15,
"eTU_type": "claim",
"Theme": "Constitutional authority and legitimacy"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "כתיבת ההכרזה נגרמה עקב הרצון להקים מדינה עצמאית בכמה שפחות זמן תוך כדי התרגשות בכדי שהבריטים יפסיקו לשלוט בארץ",
"Author": "MV",
"DU_id": 5,
"eTU_id": 16,
"eTU_type": "claim",
"Theme": "Constitutional authority and legitimacy"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "בהכרזה יש חוקים הנוגדים את עצמם למשל כמו שוויון והעדפת יהודים",
"Author": "MV",
"DU_id": 5,
"eTU_id": 17,
"eTU_type": "claim",
"Theme": "Internal contradictions in the Declaration"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "מיכאל , באופן כללי אני מבינה את הנקודה שלך אבל לא ברור לי למה השתמשת בגרשיים במילה חוקים . בנוסף , אשמח לדעת איפה לדעתך היא מבולגנת ועל מה אתה מבסס את זה ?",
"Author": "AS",
"DU_id": 6,
"eTU_id": 18,
"eTU_type": "question",
"Theme": "Internal contradictions in the Declaration"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "אני מסכימה , עם עלמה מגילת העצמאות כן מהווה מין בסיס לחוקים או אמנה חברתית",
"Author": "MM",
"DU_id": 7,
"eTU_id": 19,
"eTU_type": "claim",
"Theme": "Legal status of the Declaration of Independence"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "ואני מסכימה שיש לה מקום גדול בהיסטוריה",
"Author": "MM",
"DU_id": 7,
"eTU_id": 20,
"eTU_type": "claim",
"Theme": "Historical vs. legal significance"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "איך את חושבת שהשוני ייראה אם אלה היו אנשים שנבחרו שכתבו אותה ? מה את חושבת שכתיבה מחד תעשה ? למה היא תוביל ואיך מגילת העצמאות החדשה תראה ?",
"Author": "AS",
"DU_id": 8,
"eTU_id": 21,
"eTU_type": "question",
"Theme": "Need for a new constitution"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "אםפ אין לה ערך משפטי מדוע היא עדיין חשובה ובשימוש ?",
"Author": "AS",
"DU_id": 8,
"eTU_id": 22,
"eTU_type": "question",
"Theme": "Historical vs. legal significance"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "בעד : כותבי ההכרזה מהווים קבוצות שונות באוכלוסייה",
"Author": "MV",
"DU_id": 9,
"eTU_id": 23,
"eTU_type": "claim",
"Theme": "Democratic representation in constitutional drafting"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "הגרשיים נגרמו עקב חיפזון שלי , ההודעה עצמה טעות",
"Author": "MV",
"DU_id": 9,
"eTU_id": 24,
"eTU_type": "meta",
"Theme": "Democratic representation in constitutional drafting"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "הגרשיים בהתחחלה עוד פעם טעות ששכחתי לשנות",
"Author": "MV",
"DU_id": 9,
"eTU_id": 25,
"eTU_type": "meta",
"Theme": "Democratic representation in constitutional drafting"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "למה אתה מתכוון בכך שאתה טוען שמגילת העצמאות " מאוד מבולגנת " ? ואיך ניתן לקבוע שזה מה שמבטא את החזון של המדינה ואת ה"אני המאמין " ?",
"Author": "MM",
"DU_id": 10,
"eTU_id": 26,
"eTU_type": "question",
"Theme": "Internal contradictions in the Declaration"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "מגילת העצמאות נכתבה לפני זמן רב ואולי לא משקפת את החזון של האנשים כיום",
"Author": "MM",
"DU_id": 10,
"eTU_id": 27,
"eTU_type": "claim",
"Theme": "Historical vs. legal significance"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "מהם החוקים האלו שאת מדברת , איזה חוקי אין שצריך להיות ?",
"Author": "MV",
"DU_id": 11,
"eTU_id": 28,
"eTU_type": "question",
"Theme": "Need for a new constitution"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "לגבי מה שמאיה כתבה , למה הצורה של המגילה בעייתית לדעתך ובאיזו צורה את רוצה להבהיא את המעמד שלה ?",
"Author": "MV",
"DU_id": 11,
"eTU_id": 29,
"eTU_type": "question",
"Theme": "Need for a new constitution"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "לגבי מה שסטנלי כתב , זה נכון שאין לה מעמד משפטי אמיתי , אך זה אפשר לשנות , בשביל לשנות נצטרך חוקה שהרוב הכולל של אנשים יאשרו אותה . איך לדעתך צריך לעשות זאת ?",
"Author": "MV",
"DU_id": 11,
"eTU_id": 30,
"eTU_type": "question",
"Theme": "Need for a new constitution"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "כאשר התכוונתי ב"מאוד מבולגנת " , התכוונתי שבמגילה עצמה אין רק חוקים . במגילה , בחצי מהשורות בכלל כתוב למה יהודים צריכים לקבל מדינה משל עצמם - עד פסקה 10",
"Author": "MV",
"DU_id": 12,
"eTU_id": 31,
"eTU_type": "claim",
"Theme": "Internal contradictions in the Declaration"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "ובכללי במגילה כתוב רק הרבה מלל שלפי דעתי לא צריך להימצא בחוקה , צריך שיהיה רק את התכלס",
"Author": "MV",
"DU_id": 12,
"eTU_id": 32,
"eTU_type": "claim",
"Theme": "Internal contradictions in the Declaration"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "במגילה זו נכללים חוקים מאוד חושבים כגון החירות והצדק , אך לפי דעתי החוקים האלו היו יכולים להיכתב גם בלי המגילה",
"Author": "MV",
"DU_id": 12,
"eTU_id": 33,
"eTU_type": "claim",
"Theme": "Need for a new constitution"
},
{
"Title": "The Legal and Constitutional Status of Israel's Declaration of Independence",
"Text": "לכן , מה שצריך לעשות זה לכתוב חוקה חדשה לגמרי בלי שקר למגילת העצמאות , ולקחת את המגילה בתור משוב להאם ולהסתכל האם פספסנו משהו בחוקה שהיה כתוב במגילה",
"Author": "MV",
"DU_id": 12,
"eTU_id": 34,
"eTU_type": "claim",
"Theme": "Need for a new constitution"
}
]
"""
if name == 'main':
# Step 1: Read full raw text (replace this with reading from file if needed)
# with open("your_input_file.txt", encoding="utf-8") as f:
# text = f.read()
# Step 2: Extract just the JSON array content using regex
json_match = re.search(r"(\[\s*{.*?}\s*\])", text, re.DOTALL)
if not json_match:
raise ValueError("No JSON array found in the text.")
json_array_str = json_match.group(1)
# Step 3: Fix invalid quotes inside values (a bit hacky but works for most cases)
# Replace smart quotes or embedded double-quotes in values
def clean_json_string(json_str):
# Escape inner quotes only inside values (naively fix bad formatting)
json_str = re.sub(r'("Text":\s*")([^"]*?)(?<!\\)(")',
lambda m: m.group(1) + m.group(2).replace('"', '\\"') + m.group(3), json_str)
return json_str
cleaned_json_str = clean_json_string(json_array_str)
# Step 4: Load JSON safely
try:
data = json.loads(cleaned_json_str)
except json.JSONDecodeError as e:
print("Failed to parse JSON:", e)
raise
# Step 5: Convert to DataFrame
df = pd.DataFrame(data)
# Done! Display the DataFrame
print(df.head())
The core issue you're facing stems from this part of your data:
jsonCopyEdit"Text": "לפי דעתי מגלית העצמאות כוללת " חוקים " שבסך הכל מאוד נכונים והגיוניים , אך ההכרזה עצמה מאוד מבולגנת ומלאה סיבות ללמה היה צריך להקים את מדינת ישראל"
The unescaped double quotes (" חוקים ") within the string are breaking the JSON format, and your current clean_json_string() function doesn't robustly escape them in every case.
✅ Fix
You should enhance the regular expression logic so that it recursively escapes inner double quotes inside all values — not just for "Text" fields.
Instead of using a regular expression, the most reliable solution is to parse the entire JSON array as raw text, fix the quotes before parsing it with json.loads().
✅ Better Solution Using ast.literal_eval and Pre-Cleaning:
Here's how to fix it more reliably:
pythonCopyEditimport pandas as pd
import json
import re
def extract_and_clean_json(text):
# Step 1: Extract JSON array
json_match = re.search(r"([\s*{.?}\s])", text, re.DOTALL)
if not json_match:
raise ValueError("No JSON array found in the text.")
raw_json = json_match.group(1)
# Step 2: Clean double quotes inside strings using smarter regex
# This escapes " inside text fields
def escape_inner_quotes(match):
key, value = match.group(1), match.group(2)
# Escape only double quotes inside the value (not the enclosing ones)
escaped_value = value.replace('"', '\\"')
return f'"{key}": "{escaped_value}"'
# Apply to all "key": "value" pairs
cleaned_json = re.sub(
r'"(Text)":\s*"([^"]*?")([^"]*?)"',
lambda m: f'"{m.group(1)}": "{m.group(2).replace("\"", "\\\"")}{m.group(3)}"',
raw_json
)
# Final cleanup for any remaining unescaped inner quotes in 'Text' or other fields
cleaned_json = re.sub(
r'("Text":\s*")((?:[^"\\]|\\.)*)(")',
lambda m: f'{m.group(1)}{m.group(2).replace(\'"\', r\'\\\"\')}{m.group(3)}',
cleaned_json
)
return cleaned_json
-- Main Execution --
if name == 'main':
cleaned = extract_and_clean_json(text)
try:
data = json.loads(cleaned)
except json.JSONDecodeError as e:
print("JSON Decode Error:", e)
raise
df = pd.DataFrame(data)
print(df.head())
🔍 Why This Works
It targets double quotes inside values more reliably.
You don’t need to depend on ast.literal_eval() or dangerously replace " globally.
It keeps structure intact for all JSON keys.
✅ Alternative (Best Practice)
If you control the input, it's best to fix the original data to escape quotes inside Text fields, like:
jsonCopyEdit"Text": "לפי דעתי מגלית העצמאות כוללת \" חוקים \" ..."
If not, stick to the regex-cleaning workaround.
Let me know if you want me to help clean the whole input for you programmatically.