In my IntelliJ editor, I have a test.json file as below. The second json record displays an error message "Json standard only allows one top-level value". But this is a valid JSON file, right? How to get rid of this annoying message?
{"reviewerID": "A2XVJBSRI3SWDI", "asin": "0000031887", "reviewerName": "abigail", "helpful": [0, 0], "title": "Ballet Dress-Up Fairy Tutu", "url": "https://www.amazon.com/dp/0000031887", "brand": "Boutique Cutie", "reviewText": "Perfect red tutu for the price. I baught it as part of my daughters Halloween costume and it looked great on her.", "overall": 5.0, "summary": "Nice tutu", "unixReviewTime": 1383523200, "reviewTime": "11 4, 2013"}
{"reviewerID": "A2G0LNLN79Q6HR", "asin": "0000031887", "reviewerName": "aj_18 \"Aj_18\"", "helpful": [1, 1], "title": "Ballet Dress-Up Fairy Tutu", "url": "https://www.amazon.com/dp/0000031887", "brand": "Boutique Cutie", "reviewText": "This was a really cute tutu the only problem is that it was super short on my 5 yr old daughter. Other than that it was really adorable.", "overall": 4.0, "summary": "Really Cute but rather short.", "unixReviewTime": 1337990400, "reviewTime": "05 26, 2012"}
You have to combine them as [ {Obj 1}, {Obj 2} ] if you want to use them in the same json file. Otherwise the json file will be containing two dictionary objects and it can only have one top level object.
Related
I'm getting information from an external api. I'm getting an error when I try to update the database as the string formatting is incorrect.
There is a mixture of Double quotes and single quotes caused by the single quote O' in the first line which must tell python to use Double quotes.
To get over this I tried json.dumps() and that gives me the result below and causes a syntax error when inserting to the Database, because of the single quotes around every object.
[
'{"author_name": "Michael P O\'Shaughnessy", "rating": 4, "text": "Stayed for a midweek"}',
'{"author_name": "camille williams", "rating": 5, "text": "We looked around and found"}',
'{"author_name": "natasha sevrugina", "rating": 5, "text": "Stayed at the "}',
'{"author_name": "niamh kelly", "rating": 5, "text": "Great hotel in a central location"}',
'{"author_name": "Janette Wade", "rating": 5, "text": "Excellent staff
\\ud83d\\udc4f\\n\\nJanette\\nSpiritual Ceremonies"}'
]
It should look like this to achieve, valid Json
[
{"author_name": "Michael P O\' Shaughnessy", "rating": 4, "text": "Stayed for a midweek night"},
{"author_name": "camille williams", "rating": 5, "text": "We looked around and found"}
]
With out jsondumps the return from the api is, notice only the first line is changed
[
{'author_name': "Michael P O'Shaughnessy", 'rating': 4, 'text': "Stayed for a midweek night"}
{'author_name': 'camille williams', 'rating': 5, 'text': 'We looked around and found that was great."},
{'author_name': 'natasha sevrugina', 'rating': 5, 'text': 'Stayed at the Hotel '},
{'author_name': 'niamh kelly', 'rating': 5, 'text': 'Great hotel in a central location. '},
{'author_name': 'Janette Wade', 'rating': 5, 'text': 'Modern rooms. Great room service. '}
]
Which also gives a syntax error because of the mixture of single, double and single quotes.
Here are my calls to the api:
review_author = dictionary['result']['reviews'][i]['author_name']
review_rating = dictionary['result']['reviews'][i]['rating']
review_text = dictionary['result']['reviews'][i]['text']
dict_keys = ["author_name", "rating", "text"]
res_dict = {dict_keys[0]: review_author, dict_keys[1]: review_rating, dict_keys[2]: review_text}
bus_reviews.append(json.dumps(res_dict))
How can I remove the single quotes around json.dump()
I changed this
bus_reviews.append(json.dumps(res_dict))
to
bus_reviews.append(res_dict)
and I put the return statement to include the json dumps
return json.dumps(bus_reviews)
I have a list of dictionaries written to a data.txt file. I was expecting to be able to read the list of dictionaries in a normal way when I load, but instead, I seem to load up a string.
For example - when I print(data[0]), I was expecting the first dictionary in the list, but instead, I got "[" instead.
Below attached is my codes and txt file:
read_json.py
import json
with open('./data.txt', 'r') as json_file:
data = json.load(json_file)
print(data[0])
data.txt
"[
{
"name": "Disney's Mulan (Mandarin) PG13 *",
"cast": [
"Jet Li",
"Donnie Yen",
"Yifei Liu"
],
"genre": [
"Action",
"Adventure",
"Drama"
],
"language": "Mandarin with no subtitles",
"rating": "PG13 - Some Violence",
"runtime": "115",
"open_date": "18 Sep 2020",
"description": "\u201cMulan\u201d is the epic adventure of a fearless young woman who masquerades as a man in order to fight Northern Invaders attacking China. The eldest daughter of an honored warrior, Hua Mulan is spirited, determined and quick on her feet. When the Emperor issues a decree that one man per family must serve in the Imperial Army, she steps in to take the place of her ailing father as Hua Jun, becoming one of China\u2019s greatest warriors ever."
},
{
"name": "The New Mutants M18",
"cast": [
"Maisie Williams",
"Henry Zaga",
"Anya Taylor-Joy",
"Charlie Heaton",
"Alice Braga",
"Blu Hunt"
],
"genre": [
"Action",
"Sci-Fi"
],
"language": "English",
"rating": "M18 - Some Mature Content",
"runtime": "94",
"open_date": "27 Aug 2020",
"description": "Five young mutants, just discovering their abilities while held in a secret facility against their will, fight to escape their past sins and save themselves."
}
]"
The above list is formatted properly for easy reading but the actual file is a single line and the different lines are denoted with "\n". Thanks for any help.
remove double quote in data.txt is useful for meγ
eg. modify
"[{...},{...}]"
to
[{...},{...}]
Hope it helps!
This is a snippet of a JSON file that was returned by TMDB and I'm trying to access the title of every object. I've tried using the following methods like from this post How to access specific value from a nested array within an object array.
"results": [
{
"vote_count": 2358,
"id": 283366,
"video": false,
"vote_average": 6.5,
"title": "Miss Peregrine's Home for Peculiar Children",
"popularity": 20.662756,
"poster_path": "/AvekzUdI8HZnImdQulmTTmAZXrC.jpg",
"original_language": "en",
"original_title": "Miss Peregrine's Home for Peculiar Children",
"genre_ids": [
18,
14,
12
],
"backdrop_path": "/9BVHn78oQcFCRd4M3u3NT7OrhTk.jpg",
"adult": false,
"overview": "A teenager finds himself transported to an island where he must help protect a group of orphans with special powers from creatures intent on destroying them.",
"release_date": "2016-09-28"
},
{
"vote_count": 3073,
"id": 381288,
"video": false,
"vote_average": 6.8,
"title": "Split",
"popularity": 17.488396,
"poster_path": "/rXMWOZiCt6eMX22jWuTOSdQ98bY.jpg",
"original_language": "en",
"original_title": "Split",
"genre_ids": [
27,
53
],
"backdrop_path": "/4G6FNNLSIVrwSRZyFs91hQ3lZtD.jpg",
"adult": false,
"overview": "Though Kevin has evidenced 23 personalities to his trusted psychiatrist, Dr. Fletcher, there remains one still submerged who is set to materialize and dominate all the others. Compelled to abduct three teenage girls led by the willful, observant Casey, Kevin reaches a war for survival among all of those contained within him β as well as everyone around him β as the walls between his compartments shatter apart.",
"release_date": "2016-11-15"
},
var titles = results.map(function extract(item){return item.title})
The map function iterates through the array and builds the resulting array by applying the extract function on each item.
for (var i =0; i < obj.results.length; i++) {
console.log(obj.results[i].title);
}
First, we get the results key, and then, iterate over it since it is an array.
Results is nothing more than an array of objects, there's nothing nested.
You could use .forEach()
results.forEach(function(item){
console.log(item.title);
});
"Title": "Anti-Mage",
"Url": "antimage",
"ID": 1,
"Lore": "The monks of Turstarkuri watched the rugged valleys below their mountain monastery as wave after wave of invaders swept through the lower kingdoms. Ascetic and pragmatic, in their remote monastic eyrie they remained aloof from mundane strife, wrapped in meditation that knew no gods or elements of magic. Then came the Legion of the Dead God, crusaders with a sinister mandate to replace all local worship with their Unliving Lord's poisonous nihilosophy. From a landscape that had known nothing but blood and battle for a thousand years, they tore the souls and bones of countless fallen legions and pitched them against Turstarkuri. The monastery stood scarcely a fortnight against the assault, and the few monks who bothered to surface from their meditations believed the invaders were but demonic visions sent to distract them from meditation. They died where they sat on their silken cushions. Only one youth survived - a pilgrim who had come as an acolyte, seeking wisdom, but had yet to be admitted to the monastery. He watched in horror as the monks to whom he had served tea and nettles were first slaughtered, then raised to join the ranks of the Dead God's priesthood. With nothing but a few of Turstarkuri's prized dogmatic scrolls, he crept away to the comparative safety of other lands, swearing to obliterate not only the Dead God's magic users - but to put an end to magic altogether. ",
"SuggestedRoleLevels": {
"Carry": 2,
"Escape": 3
},
"Enabled": true,
"Side": "Radiant",
"Aliases": [
"am"
],
"AttackCapabilities": "DOTA_UNIT_CAP_MELEE_ATTACK",
"PrimaryAttribute": "DOTA_ATTRIBUTE_AGILITY",
"Initial": {
"Strength": 22,
"StrengthGain": 1.2,
"Agility": 22,
"AgilityGain": 2.8,
"Intelligence": 15,
"IntelligenceGain": 1.8,
"Health": 568,
"HealthRegen": 0.91,
"Mana": 195,
"ManaRegen": 0.61,
"Armor": 2.08,
"MagicResistance": 0.25,
"MinDamage": 49,
"MaxDamage": 53,
"AvgDamage": 51,
"IncreasedAttackSpeed": 22,
"BaseAttackTime": 1.45,
"AttackTime": 1.19,
"AttacksPerSecond": 0.84,
"AttackAnimationPoint": 0.3,
"AttackAcquisitionRange": 600,
"AttackRange": 128,
"VisionDayRange": 1800,
"VisionNightRange": 800,
"ProjectileSpeed": 0,
"MovementSpeed": 315,
"TurnRate": 0.5
},
"Abilities": [
{
"Title": "Mana Break",
"Url": "mana_break",
"HeroAbilityUrl": "antimage_mana_break",
"ID": 5003,
"Description": "Burns an opponent's mana on each attack. Mana Break deals 60% of the mana burned as damage to the target. Mana Break is a Unique Attack Modifier, and does not stack with other Unique Attack Modifiers.",
"Lore": "A modified technique of the Turstarkuri monks' peaceful ways is to turn magical energies on their owner.",
"Notes": [
"Mana Burn is blocked by spell immunity.",
"You can lifeleech the damage dealt by this skill with a Lifesteal aura."
],
"Type": "DOTA_ABILITY_TYPE_BASIC",
"Behavior": [
"DOTA_ABILITY_BEHAVIOR_PASSIVE"
],
"DamageType": "DAMAGE_TYPE_PHYSICAL",
"AbilitySpecial": [
{
"Name": "Damage Per_burn",
"Url": "damage_per_burn",
"Value": [
0.6
]
},
{
"Name": "Mana Burned Per Hit",
"Url": "mana_per_hit",
"ValueType": "FIXED",
"Value": [
28,
40,
52,
64
]
}
]
That is a slice from my json file, I wanna insert it inside a mongodb called dota2.
I was trying the command:
mongoimport --jsonArray -d dota2 -c docs --file heroes.json
the return told me:
2015-10-31T12:09:35.755-0200 connected to: localhost
2015-10-31T12:09:35.842-0200 imported 110 documents
But I won't get my data information, the command : db.dota.find()
Return empty...
Someone can help me? Yes...I am a newbie with mongodb. :/
As per your command you are inserting the data into the collection named docs present in database dota2.
So you should probably do like
use dota2;
db.docs.find();
Ok, I understand, my data are inside mongodb! But inside docs collections :) It works!
I am writing a JSON file which holds data about electronics such as tvs, consoles etc. What is the best way to categorize, let's say 3D LED tvs, from non 3D LED tvs ? Would it make more sense to put a property '3d' within an 'leds' object ? Or is it better to create a '3d' object within 'leds' ?
{"products":[
{ "tvs":[
{"samsung":[
{"leds":[
{
"product_id": "034567",
"product_name": "Samsung UA22F5100 22'' LED TV (Black)",
"model_no": "UA22F5100",
"brand": "Samsung",
"price": 399,
"screen_size": 22,
"screen_res": "1920 x 1080",
"usb": 1,
"hdmi": 1,
"screen_format": "LED",
"dimensions": "513.1 x 366.5 x 169.6",
"manuf_guarantee": "1 year"
}
]}
]}
]}
]}