Python3 JSON parse with duplicate keys - json

Sorry for the newbie question, there is a json response like this;
import json
jsonObj = json.loads("""
{
"data": [
{
"name_space": "name",
"value": "Angelina"
},
{
"name_space": "surname",
"value": "Jolie"
},
{
"name_space": "year",
"value": "1975"
}
]
}
""")
and I am currently able to parsing this way
for meta in jsonObj['data']:
if meta['name_space'] == 'name':
print(meta['value'])
if meta['name_space'] == 'surname':
print(meta['value'])
if meta['name_space'] == 'year':
print(meta['value'])
I'm researching if there are different ways to do this and make the code look cleaner or simpler.

clean_dict = {x['name_space']: x['value'] for x in jsonObj['data']} would give you the following dict:
{'name': 'Angelina', 'surname': 'Jolie', 'year': '1975'}
That code uses the x['name_space'] value as your new keys in the dict.
Then you should be able to print it however you'd like, such as print(clean_dict.values()).

Related

a strange json format

Can someone help me with the following JSON format.
deals: {
'obj-1': { id: '1', name: 'a', text: 'text' },
'obj-2': { id: '2', name: 'b', text: 'text' }
}
I'm doing a tutorial step by step and found this type of JSON, but I have doubts on how to reproduce it.
JSON
I understood that it is an object with several other objects.
bringing from my backend this would seriously list objects like that.
{
"deals": [
{
"id": "1",
"name": "a",
"text": "text"
},
{
"id": "2",
"name": "b",
"text": "text"
}
]
}
starting now with react and I'm trying to understand a lot.
can someone help me to reproduce in this way or even explain a little more about this model?
create an object with several objects and name each one!
QUESTION: how to convert from the format that my backend returns me to that different format?
Using forEach on backend.deals, you can extract each of the deals and assign it to data as an object:
const data = { deals: {}};
backend.deals.forEach(deal => { data.deals[`obj-${deal.id}`] = deal });
console.log(data);

How to add root node in JSON for every object?

I convert excel file to JSON , to import it into my firebase DB.
On conversion, I have the JSON data in below format
[
{
"ProductNumber": "7381581",
"SKU": "test3",
},
{
"ProductNumber": "7381582",
"SKU": "test",
},
{..}
]
But I need it like this
{
"7381581" :{
"ProductNumber": "7381581",
"SKU": "test3",
},
"7381582":{
"ProductNumber": "7381582",
"SKU": "test",
},{..}
}
How can I make changes to the spreadsheet records to get the JSON in the above format ? (OR)
How should I add the key values to JSON dynamically?
You can use reduce as suggested to iterate over the original array and transform it into an object.
data.reduce((prev, current) => {
prev[current.ProductNumber] = current;
return prev;
}, {});
You can see a working example in the playground here.

Ruby: How to parse json to specific types

I have a JSON that I want to parse in Ruby. Ruby is completely new to me, but I have to work with it :-)
Here is my litte snippet, that should do the parsing:
response = File.read("app/helpers/example_announcement.json")
JSON.parse(response)
this works pretty fine. The only downside is, I do not know the properties at the point where I use it, it is not typesafe. So I created the objects for it
class Announcements
##announcements = Hash # a map key => value where key is string and value is type of Announcement
end
class Announcement
##name = ""
##status = ""
##rewards = Array
end
And this is how the json looks like
{
"announcements": {
"id1" : {
"name": "The Diamond Announcement",
"status": "published",
"reward": [
{
"id": "hardCurrency",
"amount": 100
}
]
},
"id2": {
"name": "The Normal Announcement",
"players": [],
"status": "published",
"reward": []
}
}
}
So I tried JSON parsing like this
response = File.read("app/helpers/example_announcement.json")
JSON.parse(response, Announcements)
But this is not how it works^^can anybody help me with this?

How to check JSON request body for REST Api, for object attributes and structure?

I am writing my first api (express/node) and one of the endpoints receives json data in the body like:
{
"text": "some comment here...",
"tags": [
{"id": 0, "tag": "some tag 1"},
{"id": 123, "tag": "some tag 2"}
],
"date": "1452305028289",
}
Is there some way you can check that all the properties exist on the object and that they have values? Or do you have to write a custom function checking for each required property and values?
You can use one of these packages for validating data with NodeJS:
https://github.com/hapijs/joi
https://github.com/mafintosh/is-my-json-valid
https://github.com/ctavan/express-validator
A simple solution would be this function that takes an object and a list of strings as the properties of that object:
var checkProperties = function (obj, props) {
return props
.map(function(prop) { return obj.hasOwnProperty(prop); })
.reduce(function (p, q) { return p && q; });
}
use like this
checkProperties({ prop1: someValue, prop2: someOtherValue }, ["prop1", "prop2"]); // true

Collect list of attributes with groovy and jsonslurper into single list

What's the best way to collect a list of attributes from a JSON hierarchy? Here's what I'm trying to do:
import groovy.json.JsonSlurper
def jsontxt = '''
{
"lvl1": [
{
"lvl2": [
{
"lvl3": [
{
"a1": false,
"a2": {
"a2b1": false,
"a2b2": false
},
"a3": "wantvalue1"
},
{
"a1": false,
"a2": {
"a2b1": false,
"a2b2": false
},
"a3": "wantvalue2"
}
],
},
],
}
]
}
'''
def jsresult = new JsonSlurper().parseText(jsontxt)
def mytry = jsresult.lvl1.lvl2.lvl3.collect{it.a3} // [[[wantvalue1, wantvalue2]]]
assert ["wantvalue1","wantvalue2"] == mytry
Apologies the input is not as clean as it could be but I didn't want to lose my situation.
What I want is a basic list without the additional empty lists. I know there must be a really cool way to do this but I'm not groovy enough for it. . . help??
Pretty close. Try flatten().
Try jsresult.lvl1.lvl2.lvl3.collect{it.a3}.flatten() or myTry.flatten()