I have a JSON that comes to me from an API and I need to structure that JSON to give it a certain format.
My pure JSON is this:
{
"457":{
"1":{
"value":"4.12",
"timestamp":1534183021
},
"2":{
"value":"38.8",
"timestamp":1534183021
},
"3":{
"value":"37.2",
"timestamp":1534183021
},
"4":{
"value":"216.0",
"timestamp":1534183021
}
}
}
This is the JSON I need:
{
"1":{
"type":"float",
"value":4.12,
"metadata":{
"timestamp":{
"value":1534183021,
"type":"Integer"
}
}
},
"2":{
"type":"float",
"value":38.8,
"metadata":{
"timestamp":{
"value":1534183021,
"type":"Integer"
}
}
},
"3":{
"type":"float",
"value":37.2,
"metadata":{
"timestamp":{
"value":1534183021,
"type":"Integer"
}
}
},
"4":{
"type":"float",
"value":216.0,
"metadata":{
"timestamp":{
"value":1534183021,
"type":"Integer"
}
}
}
}
My problem is that since my original JSON does not have labels, I am not sure how I can assign the values to it. Previously, in these cases, I have used something like this, but here I do not know how to treat it.
loop through the JSON and do this.
var medidas_inver = {
name: params.contextResponses[i].contextElement.attributes[j].name,
type: params.contextResponses[i].contextElement.attributes[j].type,
value: params.contextResponses[i].contextElement.attributes[j].value,
timestamp: params.contextResponses[i].contextElement.attributes[j].metadatas[k].value
};
How can I get that structure that I have commented?
Being
data
the JSON you get, you can do:As long as the structure of this JSON returned by the API is maintained.
I think you are confusing two things:
A data structure made up of arrays and maps, and
A String representation of that data structure, and matching the syntax that would be used in Javascript to define that structure.
JSON is just the latter; once you load the structure in Javascript you no longer work with JSON but with arrays and maps.
If you have:
with
data["457"]
you havewith
data["457"]["2"]
you haveetc.
If you want to add a field, then you do (eg).
None of the above is JSON, everything is pure Javascript.