a strange json format - json

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);

Related

Python3 JSON parse with duplicate keys

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()).

How to parse JSON data with custom object names?

I want to parse a JSON with Typescript, where object names can vary and I have no way to know them all. For example:
{
"planets": {
"Alderaan": {
"available_items": {
"Cinamone": {
"available": 74,
"buy_price": 6,
"sell_price": 6
},
"Dwimeryt": {
"available": 42,
"buy_price": 12,
"sell_price": 11
}
}
}
}
Where there can be many planets with different names.
I figured out that in order to parse JSON object successfully, we need to have corrent variable names, so for example that works:
interface MyObj {
x: number;
y: number:
}
let json_string = `{
"x": 5,
"y": 12
}`;
let test: MyObj = JSON.parse(json_string);
But if we change variable name in interface from "x" to lets say "xx" it becomes undefined after parsing. That creates seemingly unsolvable problem if we cant know all of the JSON object names, because I cant create an interface withh all of the planet names. Am I missing something? How would you parse a JSON I have posted?
Do you have any influence on the JSON itself? To me it seems that it is not the best way to use JSON. If I would try to design this, your JSON would look more like this:
{
"planets": [
{
"name": "Alderaan",
"available_items": [
{
"name": "Cinamone",
"available": 74,
"buy_price": 6,
"sell_price": 6
}, {
"name": "Dwimeryt",
"available": 42,
"buy_price": 12,
"sell_price": 11
}]
}]
}
This way you would always know the name of the fields and also their types. I do not think that this could be achieved easily with the current JSON format.

EXTJS map array of strings to model field values

I am using EXT JS 4.1.1.
I have a json response like this:
{ values: ["A","B","C"] }
I then have a model like so:
Ext4.define('model', {
extends: 'Ext4.data.model',
fields: [ 'name' ]
});
I am trying to create models with one value, name, that corresponds to the above json values so that I can use the name values in a ComboBox.
Ext4.define('store',{
extend: 'Ext4.data.Store',
model: 'model',
requires: 'model',
proxy: {
type: 'memory',
reader: {
type: 'json',
root: 'values',
successProperty: 'success'
}
}
});
The issue I'm having is that when populating my ComboBox with the name attribute, it is empty (""). The raw value is correct, it corresponds directly to the appropriate value.
How can I map this array of values correctly to a name field on my model model?
That is not actually a proper JSON response, paste it into http://jsonlint.com/ and you will see for yourself.
Instead your JSON should look like this:
{
"values": [
{
"name": "A"
},
{
"name": "B"
},
{
"name": "C"
}
]
}
Which you will see is valid if you paste into the jsonlint link above.
The store reader is expecting to see 'name' attributes in the data, but cannot, which is why you are seeing this behaviour.

Mongoose - How can I make this data more usable?

I have the following data strucutre outputting form my Schema in a node/express app. I'd like to have the feeds array simply an array of name:key pairs. I don't like the sort of weird numbered object structure going on between "feeds" and the actual feeds data. But i can't figure out how to manually define that in mongoose. any help would be awesome. thanks!
outputted JSON
{
"title": "Testing",
"created_at": "2011-10-05T16:23:26.217Z",
"feeds": [{
"0": {
"name": "twitter",
"key": "person1"
},
"1": {
"name": "twitter",
"key": "person2"
},
"_id": "4e8c847e02edc10035000003"
}]
}
i want this:
{
"title": "Testing",
"created_at": "2011-10-05T16:23:26.217Z",
"feeds": [
{
"name": "twitter",
"key": "person1"
},
{
"name": "twitter",
"key": "person2"
}
],
"_id": "4e8c847e02edc10035000003"
}
this is my schema:
var Feed = new Schema({
name : { type: String }
, key : { type: String }
});
var Page = new Schema({
title : { type: String, required: true, index: { unique: true } }
, feeds : [Feed]
, created_at : { type: Date, required: true, default: Date.now }
});
Ok, a colleague was able to answer this for me. My bad for not posting the relevant code, I didn't realize where the problem actually was. But for those who may encounter this problem:
If you push your embedded docs into the model when saving, you may need to do a forEach loop rather than pushing the embedded docs (in this case Feeds) together. Using forEach, the database saved the feeds directly to the feeds array rather than creating those weird groupings.
This pushed the feeds in properly:
req.body.feed.forEach(function(feed){
page.feeds.push(feed);
});
Let me know if you have the same problem and need more explanation.

extJS: reading a nested JSON

I have a pretty nested JSON coming from a ldap_search() call. I would like to use this information to populate an ExtJS ComboBox, but I am facing some troubles with the reader. Apparently, I am not able to read the information that I need in the ComboBox, that is the mail address of the people, the uid and the cn
I think the whole problem lies in the store. I was trying the following code:
var store= new Ext.data.JsonStore({
url:'search.php',
root: '',
totalProperty: 'count',
fields: [
{name:'cn', type: 'string', mapping:'cn.0'},
{name:'mail', type: 'string', mapping:'mail.0'},
{name:'uid', type: 'string', mapping:'uid.0'}
]
});
but FireBug told me missing ; before statement return obj.cn.0 in ext-all.js (line 7). I tried with another, easier JSON array and it works, that is why I really think the problem lies in this part of code, especially in the mapping.
an example of JSON returned by search.php is:
{
"count": 2,
"0": {
"mail": {
"count": 1,
"0": "Mail address not registered."
},
"0": "mail",
"uid": {
"count": 1,
"0": "name0.surname0#domain.com"
},
"1": "uid",
"cn": {
"count": 1,
"0": "Surname0 Name0"
},
"2": "cn",
"count": 3,
"dn": "cn=Surname0 Name0,ou=personal,dc=domain,dc=com"
},
"1": {
"mail": {
"count": 1,
"0": "name1.surname1#domain.com"
},
"0": "mail",
"uid": {
"count": 1,
"0": "name1.surname1"
},
"1": "uid",
"cn": {
"count": 1,
"0": "Surname 1 Name 1"
},
"2": "cn",
"count": 3,
"dn": "cn=Surname1 Name1,ou=personal,dc=domain,dc=com"
}
}
Thanks for your time.
Yep, that JSON structure is not going to work straight away with standard ExtJS JSONReader. Take a look at this example taken from the ExtJS API documentation on how the JSON should look like.
{
results: 2000, // Reader's configured totalProperty
rows: [ // Reader's configured root
// record data objects:
{ id: 1, firstname: 'Bill', occupation: 'Gardener' },
{ id: 2, firstname: 'Ben' , occupation: 'Horticulturalist' },
...
]
}
Also, the root config option is required, you cannot leave it empty. In the above example your root would be "rows".
You are probably going to need to parse that JSON of yours into a simpler format at first, before feeding it to the JSONReader.
I was looking to do the same thing, but have one of the nested items be a field in my chart. This post kept coming up, so I thought it might be helpful to see what I did to solve the chart issue. The key to solving it is knowing that the label config exists: http://docs.sencha.com/ext-js/4-0/#!/api/Ext.chart.Label. Using that you can override the default render of what you pass in. In this example the field is "key" (Not shown here, but my model is using the default type for 'key' (ie., not string)). The key object gets passed to renderer. Using function(t), I can now access that object like javascript and pass back the name under the object.
json
key : {
wholePath : "c:/.../fileName.txt",
fileName : "fileName.txt",
}
code:
axes: [
{
title: 'Values',
type: 'Numeric',
position: 'left',
fields: ['value'],
minimum: 0,
maximum: 100,
minorTickSteps: 1
},
{
title: 'File Name',
type: 'Category',
position: 'bottom',
fields: ['key'],
label: {
renderer: function(t) {
var fileName = t.name;
return fileName;
}
}
}