使用Notepad++编写的JSON文件导入MongoDB报错,请求排查
Hey there! Let's break down why your import is failing and how to fix it. I took a close look at your JSON content and found two critical issues—one that's directly triggering the syntax error you're seeing, and another that'll cause problems even after you fix the first one.
1. Incomplete JSON Syntax (The Immediate Error)
Your JSON is missing the closing curly brace } for the outermost object. Right now, it ends with the closing bracket of the blog array, but the entire document starts with an opening { that never gets closed. That's why the parser is throwing an error about an invalid character—it can't properly finish parsing the object.
Here's the corrected, fully valid JSON:
{"User": {"fname": "Brian", "lname": "Watkins", "user_id": "1", "email": "brian.watkins@yahoo.com", "follows": ["1"], "likes": ["18"]}, "blog": [{"title": {"$title": "Peanut Butter and Jelly Sandwich"}, "feed": "Ingredients are pe..."}]}
2. Reserved Character in MongoDB Field Name (A Hidden Pitfall)
Even after fixing the syntax, you'll hit another error because of the $title field name. MongoDB reserves the $ character for special operators (like $set, $match), so field names can't start with $.
To fix this, rename that field to something that doesn't use a leading $. For example, you could simplify the title structure entirely if you just need to store the title text:
{"User": {"fname": "Brian", "lname": "Watkins", "user_id": "1", "email": "brian.watkins@yahoo.com", "follows": ["1"], "likes": ["18"]}, "blog": [{"title": "Peanut Butter and Jelly Sandwich", "feed": "Ingredients are pe..."}]}
Or if you need to keep the nested structure, use a name like title_text instead of $title.
Quick Validation Tip
Before importing, you can paste your JSON into a JSON validation tool to double-check the syntax is perfect. Once it's valid, run your mongoimport command again—something like this:
mongoimport --db your_db_name --collection your_collection --file your_json_file.json
内容的提问来源于stack exchange,提问作者Caroline Hightower

