Update a json key inside a json file using Javascript? - javascript

I have a JSON file, I need to read that JSON file and update a particular key with new values. How can I do it with the help of javascript in the typescript file?
datafile.json:
{
"Id": {
"place": {
"operations": [{
"Name": "John",
"Address": "USA"
}]
}
}
}
Now in my test.ts file
const filepath = 'c:/datafile.json';
var testjson = filepath.Id[place][operations][0];
var mykey = 'Address';
//testjson[mykey] = 'UK';
updateJsonFile(filepath, (data) => {
data[mykey] = 'UK';
console.log(data);
return data;
});
The issue is it update the JSON with new key and values as below:
{
"Id": {
"place": {
"operations": [{
"Name": "John",
"Address": "USA"
}]
}
"Address": "UK"
}
}
But I want to just change the value of a particular key then adding new keys. Is it possible in JS.?

data doesn't have an Address property, its operations, which is inside place.
If you try to set it like
data[mykey] = 'UK';
it will create a new property to data,
It should be
o.Id.place.operations[0][mykey] = 'UK';
jsonString = `
{
"Id": {
"place": {
"operations": [{
"Name": "John",
"Address": "USA"
}]
}
}
}
`;
let o = JSON.parse(jsonString);
var mykey = 'Address';
o.Id.place.operations[0][mykey] = 'UK';
console.dir(o);

Related

How to push values to an object from inside a map function when a condition is met?

How can we push values to an object from inside a map function and return that single object. I have string comparison condition inside the map function. I tried using Object.assign but it returns an array with multiple object inside that array. Instead of this multiple object I'm expecting a single object inside an array.
Map function
let arrayObj = arrayToTraverse.map(function(item) {
var myObj = {};
if(item.inputvalue === 'Name'){
Object.assign(myObj, {name: item.value});
} else if (item.inputvalue === 'Email'){
Object.assign(organizerInfo, {email: item.value});
} else if (item.inputvalue === 'Company'){
Object.assign(organizerInfo, {company: item.value});
}
return myObj;
});
console.log("The array object is", arrayObj)
This return the array of objects as follows
[
{
"name": "Tom"
},
{
"email": "tom#abc.com"
},
{
"company": "ABC"
}
]
But The array I'm expecting is
[
{
"name": "Tom",
"email": "tom#abc.com",
"company": "ABC"
}
]
// or
[
"returned": {
"name": "Tom",
"email": "tom#abc.com",
"company": "ABC"
}
]
An example of arrayToTraverse can be considered as following
[
{
"id": "1",
"inputvalue": "Name",
"value": "Tom",
"type": "Short Text"
},
{
"id": "2",
"inputvalue": "Email",
"value": "tom#abc.com",
"type": "Email ID"
},
{
"id": "3",
"inputvalue": "Company",
"value": "Google",
"type": "Long Text"
}
]
Simply put, you're trying to reduce an array to a single object, not map one array to another.
var arrayToTraverse = [
{inputvalue:"Name",value:"Tom"},
{inputvalue:"Email",value:"tom#abc.com"},
{inputvalue:"Company",value:"ABC"},
{inputvalue:"Foo",value:"Bar"} // wont show up
];
var valuesRequired = ["Name","Email","Company"];
var result = arrayToTraverse.reduce( (acc, item) => {
if(valuesRequired.includes(item.inputvalue))
acc[item.inputvalue.toLowerCase()] = item.value;
return acc;
}, {});
console.log(result);
Edit: Added lookup array for required fields.

how to destructure an array of objects in JavaScript

I have an object "data" from 'https://randomuser.me/api/' which I'm using in my project.
{
"results": [
{
"gender": "female",
"name": {
"title": "miss",
"first": "mia",
"last": "sutton"
}
}
]
}
I destructured results from the data object as follows;
const {results} = data;
How do I destructure the results variable I created, and obtain the first item from it I want the de-structured array item to be declared as profile. This represents the profile data for the user gotten from the API call that I want to display in my app.
You can do it like this:
const { results: [firstItem] } = data;
See this MDN article for more info on destructuring.
const data = {
"results": [
{
"gender": "female",
"name": {
"title": "miss",
"first": "mia",
"last": "sutton"
}
}
]
};
// declare a const variable named firstItem that holds the first element of the array
const { results: [firstItem] } = data;
// You could event destructure the content of this first array item like this
const { results: [{ gender, name }] } = data;
// or go deeper like this
const { results: [{ name: { title, first, last } }] } = data;
console.log(firstItem);
console.log(gender);
console.log(name);
console.log(title, first, last);
According to your code (see comments), this should work too:
const data = {
"results": [
{
"gender": "female",
"name": {
"title": "miss",
"first": "mia",
"last": "sutton"
}
}
]
};
const displayUserPhotoAndName = (data) => {
if(!data) return;
const { results } = data;
const { results: [profile] } = data;
console.log(profile);
}
displayUserPhotoAndName(data);

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