Writing a JSON file a string - javascript

could someone give me some direction on how to write a piece of JSON text in JavaScript. eg
{
"Header.MainsiteURL": "http://www.ford.es",
"Header.backToMainsiteMobile": "ES-Main site"
}

You can declare a single Json object using the following syntax.
var person = {
Name: "NameOfPerson",
Age: 23
}
The following is a Json array for storing people's names and age.
var people = [
{
Name: "NameOfPerson",
Age: 23
},{
Name: "NameOfAnotherPerson",
Age: 12
}
]
What you seem to be missing in your example are the properties of the object.

Related

HashMap with List as a value in Typescript

I am learning TypeScript and am trying to create a collection similar to the following in Java
HashMap<String, List<String>> hashMap = new HashMap<String,List<String>>();
I am unable to find any examples . Is it possible to do this in Typescript? Is there something similar to this?
HashMap contains only unique keys. So you can use simple object and assign array to key:
let hash = {};
hash["bobtail"] = [];
hash["bobtail"].push({ age: 7, name: "miffy" });
console.log(hash)
Or try to use Record<Keys, Type>. As docs says:
Constructs an object type whose property keys are Keys and whose
property values are Type. This utility can be used to map the
properties of a type to another type.
interface CatInfo {
age: number;
name: string;
}
type CatBreed = "bobtail" | "birman" | "maine";
const cats: Record<CatBreed, CatInfo[]> = {
bobtail: [{ age: 7, name: "miffy" }],
birman: [{ age: 8, name: "moorzik" }],
maine: [{ age: 17, name: "mordred" }],
};
UPDATE:
This is the way to add an item to Record<Keys, Type>:
cats["bobtail"].push({ age: 11, name: "miffy" });
This is the way to get items from Record<Keys, Type>:
const bobtails: CatInfo[] = cats["bobtail"];

Why does '.includes' work on an object inside a looped array?

I was hoping someone could help me understand something about the '.includes' method.
My understanding was that this only worked on arrays? for e.g. myarray.includes('something').
But it also seems to work when you loop over the array and use it on an object for e.g:
var people = [
{
name: 'Joe',
age: 27
},
{
name: 'Rob',
age: 25
},
{
name: 'Dave',
age: 22
}
];
for(i=0; i<people.length; i++) {
console.log(people[i].name.includes('Joe')) // True
}
Can someone explain why this is?
Thanks,
Joe
Because name is of type string, which also has an includes method. You can read on that here.

Is this JavaScript two dimensional array?

const monsters = {
'1': {
name: 'godzilla',
age: 250000000
},
'2': {
Name: 'manticore',
age: 21
}
}
I learn JavaScript from Codecademy, What does this code mean?
Is this two dimensional array? If not, what is it?
The data structure you are showing in your code example is not an array at all, it is an object. Arrays are defined using square brackets ([]) and their keys (indices) are not explicitly declared but rather assigned automatically.
So if you wrote your code like this, for example, you would have an array containing objects:
const monsters = [
{
name: 'godzilla',
age: 250000000
},
{
name: 'manticore',
age: 21
}
]
…so you could access the values by their array index, like so.
monsters[0].name; // godzilla
monsters[1].name; // manticore

Create a simple rank array using map function (JavaScript)

So essentially I have a JSON that it's in the format as so:
JSON= [
{username: foo, score: 12343},
{username: bar, score: 9432},
{username: foo-bar, score: 402, ...
]
I know that the JSON that I am getting back is already rank from highest to lowest, based on the scores.
How can I make an array that automatically inserts the rank position? For instance, I would like to see an output of :
[1, username: foo, score: 12343],
[2, username: bar, score: 9432],
[3, username: foo-bar, score: 402],...
Javascript got you covered already. An array always has indexes, though it starts at zero. If you want the best, just use
console.log(JSON[0]);
and if you insist on 1 being 1, try this
function getByRank(index) {
return JSON[index - 1];
}
so you will get the best with
console.log(getByRank(1)); // {username: "foo", score: 12343}
I think in your code the json is valid json, see the " around foo...
Your syntax seems off, but assuming that the JSON is:
JSON = [
{username: 'foo', score: 12343},
{username: 'bar', score: 9432},
{username: 'foo-bar', score: 402}
]
Since Arrays are 0 indexed and you have access to the current index in a .map method, you can do something along the following:
JSON = JSON.map(function (record, index) {
record.rank = index + 1;
return record;
})
This should give you the following output:
[
{ rank: 1, username: 'foo', score: 12343 },
{ rank: 2, username: 'bar', score: 9432},
{ rank: 3, username: 'foo-bar', score: 402}
]
Hope this helps.
Strictly from the point of view of your question, you already got the answer. I just want to enumerate some ideas, maybe they will be useful to some of you in the future:
First of all, JSON (JavaScript Object Notation) is an open-standard format that uses human-readable text to serialize objects, arrays, numbers, strings, booleans, and null. Its syntax, as the name states, is derived from JavaScript, but JSON is actually a text, a string.
A JSON string is (almost always) syntactically correct
JavaScript code.
Make sure you don't use the keyword "JSON" as the name of a variable, because JSON is actually an existing object in JavaScript, and it is used to encode to JSON format (stringify) and decode from JSON format (parse).
Just try JSON.stringify({a: 2, b: 3}); and JSON.parse('{"a":2,"b":3}'); in a JavaScript console.

Remove Attribute names from Json string

Hi lets say I have a JSON string which represent a record in a grid containing 3 columns Id, Name, Status. I'm currently writing some JavaScript logic where you can filter the rows of data by typing some text in the text box. The filter will be applied to data in all columns. So if I type "James" Record 1 below will be returned an if I type None Record 1 and 2 will be returned. The problem is if I type Id, Name, or Status which is not the data but the attribute names, all records are always returned.
Record 1
{
Id: 1,
Name: "James",
Status: "None"
}
Record 2
{
Id: 2,
Name: "Paul",
Status: "None"
}
How can I modify a JSON string so that
{ Id: 2, Name: "Paul", Status: "None"}
will become
{ 2, "Paul", "None"}
Your question is a bit unclear (and I'm afraid Matthias' edit made that matter worse).
{ Id: 1, Name: "James", Status: "None" } is not a valid JSON string, but it is a valid Javascript object. JSON strings need to have their values within quotes.
If you are indeed dealing with a JSON string, with quoted properties, and you simply want the output you've requested, you could do something like this:
var person = '{ "Id": 1, "Name": "James", "Status": "None" }';
person = person.replace(/\s*"[^"]+"\s*:/g,"");
// > person = '{ 1, "James", "None" }'
If you are dealing with a Javascript object, a simple way of getting the values without the property names would be to do something like this:
var person = { Id: 1, Name: "James", Status: "None" };
person = Object.keys(person).map(function(k) { return person[k] }).join(',');
// > person = '1,James,None'
Both options will give you a string that you could search for just the values you're interested in. In the latter scenario, you'd need to add some formatting to turn the outcome into exactly what you have requested, but then given the question I'm assuming presentation is not a big deal.
However, if at all possible, I think your code would much more closely match your intentions if you instead modified the search algorithm to inspect values and not entire objects. You haven't shown us any of the code doing the searching, though, so I can't really add suggestions for that at this point.

Categories

Resources