get json field from string identifier - javascript

Suppose I have a json that looks like this:
let jsonExample = {
"name": "foo",
"age": 43,
"number" : 13,
"id": "osaid9r"
}
My goal is to create a javascript function getField(json, fieldName) that receives a json and a string representing the field name and returns the value represented by fieldName.
getField(jsonExample, "name") = "foo"
getField(jsonExample, "number") = 13
How can I write such function?

You can write as this:
let jsonExample = {
"name": "foo",
"age": 43,
"number" : 13,
"id": "osaid9r"
}
function getField(obj, field){ return obj[field];}
console.log(getField(jsonExample,"name"));
console.log(getField(jsonExample,"number"));

let jsonExample = {"name": "foo","age": 43,"number" : 13,"id": "osaid9r"}
function getField(json, key)
{
return json[key];
}
console.log(getField(jsonExample,"number"));

Related

Create json object dynamic in nodejs

I have json :
{
"fullName": "abc",
"age": 19,
...
}
I want use Nodejs to add element in above json to object named Variables in below json
{
"variables": {
"fullName" : {
"value" : "abc",
"type" : "String"
},
"age": {
"value" : 19,
"type": "Number"
},
...
}
}
Please help me this case!
You can use Object.entries with .reduce()
let data = {
"fullName": "abc",
"age": 19,
}
let result = Object.entries(data).reduce((a, [key, value]) => {
a.variables[key] = { value, type: typeof value}
return a;
}, { variables: {}})
console.log(result);
We can first entries of that object and then map it accordingly after that we convert that object using Object.fromentries. Here is an implementation:
const obj = { "fullName": "abc", "age": 19 };
const result = Object.fromEntries(Object.entries(obj).map(([k,value])=>[k,{value, type:typeof value}]));
console.log({variable:result});
Are you looking for JSON.parse to get a struct from your file, then JSON.stringify to create a json from your struct ?

how i get the object form an array with a parameter function like this

I will only get an object in comparison the id that from is decided from the user with objects of the arrays.
var laptops = [{
"name": "Firefox",
"age": 30,
"id": "ab"
},
{
"name": "Google",
"age": 35,
"id": "cd",
"date": "00.02.1990"
},
{
"name": "Microsoft",
"id": "ef",
"age": 40
}
];
getLaptopByAsin(id: string) {
var laptop = this.laptops.find(
(laptopObject) => {
return laptopObject.name === id;
}
);
return laptop;
}
var enter = "cd";
name = this.getLaptopByAsin(enter).name;
age = this.getLaptopByAsin(enter).age;
date = this.getLaptopByAsin(enter).date;
console.log(name)
console.log(age)
console.log(date)
Your problem is that you filter on name:
this.laptops.find(
(laptopObject) => {
return laptopObject.name === id;
}
);
After fixing your issue and do some refactoring, the code becomes this:
getLaptopByAsin(id: string) {
return this.laptops.find(
laptopObject => laptopObject.id === id
);
}
Some other comments:
Try to use const instead of var more often where possible.
Saving date the way you do, might give you some headache in the future. use some standard instead, like https://en.wikipedia.org/wiki/Epoch
Avoid multiple function calls when they are not needed, save the result from getLaptopByAsin to a variable (const foundLaptop) so you don't need to iterate over the array multiple times. eg:
const foundLaptop = this.getLaptopByAsin('cd');
console.log(foundLaptop.name);
console.log(foundLaptop.age, foundLaptop.date);

How to read JSON using javascript?

I have JSON data like this -
var json = {
"details": [
{
"A": {
"Name": "mike",
"Age": 22
},
"B": {
"Name": "John",
"Age": 25
}
}
]
}
I want to read A,B points as an array.
Another way to do it with your json, Object.keys(),since your options are not in array form, can use that to convert to array form.
var json = {
"details": [
{
"A": {
"Name": "mike",
"Age": 22
},
"B": {
"Name": "John",
"Age": 25
}
}
]
}
var outputDiv = document.getElementById('output');
var options = Object.keys(json.details[0]).map(function(item){
return '<option value="'+item+'">'+ item +'</option>'
})
options.unshift('<option value="" > Please select </option>')
var select = document.getElementById('your_options');
select.innerHTML = options.join()
select.onchange = function() {
outputDiv.innerHTML = JSON.stringify(json.details[0][this.value]);
}
<label>You options</label>
<select id="your_options">
</select>
<div id="output"></div>
Lets assume you receive the following JSON from a web server
'{ "firstName":"Foo", "lastName":"Bar" }'
To access this data you first need to parse the raw JSON and form a Javascript object
let response = JSON.parse('{ "firstName":"Foo", "lastName":"Bar" }');
This forms an object which we can access relativly simply
let firstName = response["firstName"];
let lastName = response["lastName"];
Have a look at javascript documentation regarding JSON:
http://devdocs.io/javascript-json/
Examples:
JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null

Is this valid json data?

The url has following json data:
[{ "topic": "cricket",
"value": "Player [ playerid=123, category=b, high=150, total=2300]",
"place": "xyz"},
{ "topic": "cricket",
"value": "Player [ playerid=456, category=c, high=60, total=300]",
"place": "abc"},
{ "topic": "cricket",
"value": "Player [ playerid=789, category=a, high=178, total=5300]",
"place": "bnm"}]
I tried online to check whether this is valid json or not through following link: http://jsonformatter.curiousconcept.com/ it says valid. if it is, how do I access each playerid ?
It is valid JSON, but the data about the player is embedded in a random string. You can do one of two things:
Update the service to send back a different, valid JS value, for example:
"value": {
"type": "Player",
"playerid": 123,
"category": "b",
"high": 150,
"total": 2300
}
Parse the data in the value key yourself:
// Simple regex, not really "parsing"
var playerIdRE = /playerid=(\d+)/i;
var result = playerIdRE.exec(yourData[0].value);
// result[0] is the full match, while result[1] is the ID.
// Or the more complicated version that does full parsing
var format = /\s*(.*?)\s*\[\s*([^\]]+)\s*\]\s*/gi,
keyValuePair = /(\w+)=([^,\]]*),?\s*/gi
function parseComplexDataType(input) {
var result = format.exec(input),
typeName = result[1],
keyValues = result[2],
returnValue = {};
if (!typeName) return returnValue;
returnValue.typeName = typeName;
input.replace(keyValuePair, function(_, key, value) {
returnValue[key] = value;
});
return returnValue;
}
// Usage:
> parseComplexDataType("Player [ playerid=123, category=b, high=150, total=2300]")
Object {typeName: "Player", playerid: "123", category: "b", high: "150", total: "2300"}
For your purposes, it is not valid. Once the JSON is corrected, you simply need to loop through the array and read each value.
var jArray = [{
"topic": "cricket",
"value": {
"type": "Player",
"playerid": 123,
"category": "b",
"high": 150,
"total": 2300
},
"place": "xyz"
}, {
...
}]
To access the JSON data ...
for (var i=0,len=jArray.length; i<len; i++) {
console.log(jArray[i].topic, jArray[i].value.type);
}
Yes, it is. I check it via: http://jsonlint.com/
Extracting "playerid":
Initialise the string to JSONArray.
Iterate over each element in the above array.
Now, from each element extract "value".
Finally, from this string you can get "playerid" by using string methods (see the code below).
Below is the code in Java:
ArrayList<String> player_ids = new ArrayList<String>();
String s = "YOUR STRING";
JSONArray ja = new JSONArray(s);
for(int i =0; i<ja.length(); i++)
{
String value = ja.getJSONObject(i).getString("value");
int start = value.indexOf("=");
int end = value.indexOf(",");
String player_id = value.substring(start+1, end);
player_ids.add(player_id);
}
Hope it helps!!

How to transform JavaScript hashmap?

i'm trying to create a <String, Array()> map from a json object.
Imagine i got this json structure:
[
{
"userId": "123123",
"password": "fafafa",
"age": "21"
},
{
"userId": "321321",
"password": "nana123",
"age": "34"
}
]
The map i want to create would be:
key (string), value (array)
{
"userId": [
"123123",
"321321"
],
"password": [
"fafafa",
"nana123"
],
"age": [
"21",
"34"
]
}
Is it possible to do this? :/
Thanks in advance.
Demo
var json = '[{"userId" : "123123", "password": "fafafa", "age": "21"}, {"userId" : "321321", "password" : "nana123", "age" : "34"}]';
var list = JSON.parse(json);
var output = {};
for(var i=0; i<list.length; i++)
{
for(var key in list[i])
{
if(list[i].hasOwnProperty(key))
{
if(typeof output[key] == 'undefined')
{
output[key] = [];
}
output[key].push(list[i][key]);
}
}
}
document.write(JSON.stringify(output));
Outputs:
{"userId":["123123","321321"],"password":["fafafa","nana123"],"age":["21","34"]}
function mergeAttributes(arr) {
return arr.reduce(function(memo, obj) { // For each object in the input array.
Object.keys(obj).forEach(function(key) { // For each key in the object.
if (!(key in memo)) { memo[key] = []; } // Create an array the first time.
memo[key].push(obj[key]); // Add this property to the reduced object.
});
return memo;
}, {});
}
var json = '[{"userId" : "123123", "password": "fafafa", "age": "21"}, {"userId" : "321321", "password" : "nana123", "age" : "34"}]';
mergeAttributes(JSON.parse(json));
// {
// "userId": ["123123", "321321"],
// "password": ["fafafa", "nana123"],
// "age": ["21", "34"]
// }
Javascript's JSON.stringify will help you to convert any JSON compliant object model into a JSON string.

Categories

Resources