Now my json is like this
{
"1": "a",
"2": "b",
"3": "c",
}
And from this, I am going to get value like this
[
{
"id": 1,
"value": "a"
},
{
"id": 2,
"value": "b"
},
{
"id": 3,
"value": "c"
},
]
I tried to use JSON.parse() but I got unexpected token error.
How can I make this?
var data = '{ "1": "a", "2": "b", "3": "c"}';
var parsedData = JSON.parse(data);
var arr = [];
for(item in parsedData) {
arr.push({
"id": parseInt(item),
"value": parsedData[item]
});
};
console.log(arr);
Here we can create a random JSON object, and if you notice, the last value doesn't have a trailing comma. In JSON, you cannot have a trailing comma or else you will get an error. You also do not have to put numbers in double quotes in JSON. I'm not sure if that's just how your data is formatted, but you don't need to do that. After you get rid of the trailing comma, you should be able to call JSON.parse() and store the data in a JavaScript object. After that we can iterate through the valid object and push the values to the array. Since you have double quotes around the numbers in your JSON object I parsed them to integers sense that's what you look like you are trying to achieve in your final output. I'd also highlight that your data is not JSON, but it simply looks like a JSON object. We don't know if you're getting this data from a JSON file, or if you're adding it manually, but if you are adding it manually, you will need to make it a valid JSON string like I have above.
I'm guessing the problem is the last comma:
{
"1": "a",
"2": "b",
"3": "c",//<===
}
JSON doesn't allow trailing commas.
let a =
{
"1": "a",
"2": "b",
"3": "c",
}
console.log(typeof a)
When I print the type of the JSON object, it displays "object".
The JSON.parse() only using on the string type.
I tried the following code.
let a = '{"1": "a", "2": "b", "3": "c"}'
let b = JSON.parse(a)
console.log(JSON.stringify(b))
It okey to parse.
Related
I'm trying to make a quiz with HTML, CSS and JavaScript.
Now i'm trying to see if the jsonData works but i get this error message
but i can't find where the unecpected character is (it says line 1 column 2) but don't see it
Other thing am i doing it good?
I just started this year with coding
var jsonData = [
{
"q1": {
"question": "what is the Capital city of Australia ",
"answers": {
"a": "Melbourne",
"b": "Sydney",
"c": "Caneberra",
"d": "Brisbane"
},
"correctAnswers": "c"
}
},
]
const me = JSON.parse(jsonData)
console.log(me.correctAnswers);
The problems have already been pointed out in the comments by T.J Crowder and Samball, but I wanted to show you the difference between a JavaScript data structure and a JSON string that needs to be parsed so you can better understand their comments.
A JSON string needs to be parsed to JavaScript data structure (array, objects, values) for you to be able to work with the data stored in the file properly
A JavaScript object/ array etc. that you define in JavaScript is already an JavaScript data structure so no need to parse it. Please note, any valid JSON is also valid JavaScript, but not the other way round.
Here a small program to illustrate what I've just written.
// this needs to be parsed so you can access it as JS data structures
const stringData = `[
{
"q1": {
"question": "what is the Capital city of Australia ",
"answers": {
"a": "Melbourne",
"b": "Sydney",
"c": "Caneberra",
"d": "Brisbane"
},
"correctAnswers": "c"
}
}
]`;
// no need for this to be parsed, as it already is a JS data strucure (an array in this case)
const alreadyJavaScript = [
{
"q1": {
"question": "what is the Capital city of Australia ",
"answers": {
"a": "Melbourne",
"b": "Sydney",
"c": "Caneberra",
"d": "Brisbane"
},
"correctAnswers": "c"
}
}, // In JavaScript this comma is fine, in JSON it is not!
]
// parse string
const me = JSON.parse(stringData)
// now print both to see that they are in fact identical
// Keep in mind it's an array not an object!
console.log(me[0]);
console.log(alreadyJavaScript[0])
Note: While it is perfectly fine to put a , at the end of the last element in JavaScript, JSON does not allow that!
I'm trying to read the data from my json with below format but it results with undefined
My JSON as below
{
"1": "A",
"2": "B",
"3": "C",
"4": "D",
"5": "E",
"6": "F",
"key":"pair"
}
I'm parsing as below
rawdata = fs.readFileSync('data.json');
data = JSON.parse(rawdata);
console.log(data.1) //returns undefined. I tried parsing 1 to String but resulted same.
console.log(data.key) //returns pair
You can't use dot notation to access an object's property if that property's name starts with a number.
To get a the property you'll need to use square bracket notation:
let o = JSON.parse(`{
"1": "A",
"2": "B",
"3": "C",
"4": "D",
"5": "E",
"6": "F",
"key":"pair"
}`);
console.log(o['1']);
In case of dot notation to access a value, the property key must be a valid identifier
In this code, property must be a valid JavaScript identifier, i.e. a
sequence of alphanumerical characters, also including the underscore
("_") and dollar sign ("$"), that cannot start with a number. For
example, object.$1 is valid, while object.1 is not.
You can use bracket notation in this case
obj['1']
Spec: Property Accessors
You can try using rawdata = fs.readFileSync('./data.json');
This tells the script the data.json file is in the same folder as it.
And then use .data['1'] to get the value.
Example of given JSON file is as follows:
result = {
"name": "Foo",
"id": "10001",
"values": "1,2,3,4"
};
No, that is not valid JSON.
First, JSON is a string. What you have in the question is a JavaScript object literal expression assigned to the variable result.
Go to https://jsonlint.com/ , paste your file into the box, and click Validate. You will see the following output:
Error: Parse error on line 1:
result = { "name":
^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'
As you can see from the JSON specification , you can't have a variable as a top-level entity. The valid entities in a JSON string are:
a string
an object
an array
a number
Your result variable is not one of those things. It's a variable, which is only valid in JavaScript.
objLiteral = {
"name": "Foo",
"id": "10001",
"values": "1,2,3,4"
};
jsonString = '{ "name": "Foo", "id": "10001", "values": "1,2,3,4" }';
var myObj = JSON.parse( jsonString );
console.log(objLiteral);
console.log(myObj);
console.log(objLiteral.name);
console.log(myObj.name);
<pre>Sample javascript</pre>
When I try to convert below json to string, getting unexpected desired output when the value is not surrounded with double quotes:
JSON data:
[
{
"Name": "param1",
"Type": "Integer",
"Default Value": 8778
},
{
"Name": "param2",
"Type": "Float",
"Default Value": 1.4
},
{
"Name": "param3",
"Type": "String",
"Default Value": true
},
{
"Name": "param4",
"Type": "String",
"Default Value": "test"
}
]
Current result:
[{"Name":"param1","Type":"Integer","Default Value":8778}, {"Name":"param2","Type":"Float","Default Value":**1.4**}, {"Name":"param3","Type":"String","Default Value":**true**}, {"Name":"param4","Type":"String","Default Value":**"test"**}]
Expected result:
[{"Name":"param1","Type":"Integer","Default Value":**"8778"**}, {"Name":"param2","Type":"Float","Default Value":**"1.4"**}, {"Name":"param3","Type":"String","Default Value":**"true"**}, {"Name":"param4","Type":"String","Default Value":**"test"**}]
I tried below code: but it is not working.
jsondata = JSON.stringify(confTableData);
jsondata = jsondata.replace(/:(\d+|\d*\.\d+)([,\}])/g, ':"$1"$2'); // only Integer & Float type values replaced
jsondata = jsondata.replace(/:(.)([,\}])/g, ':"$1"$2'); It gives strange result.
Can anyone help me on the regex pattern to match my requirement.
The JSON spec outlines what you're seeing as standard behavior and I'd recommend that you operate on the number as a number instead of a string.
If you need to modify this for some reason, you can use a "replacer" function as shown in the JSON.stringify spec.
var numbersAsStringsJSON = JSON.stringify(myData, replacer);
function replacer(key, value) {
if (typeof value === "number") { return String(value); }
else { return value; }
}
See JSFiddle for working example.
Numbers do not need to be wrapped in double quotes. Check out some of the examples on json.org.
If you want the numbers to be strings in JSON, you can make them strings before you stringify your object, e.g.:
var data = {
"Name": "param1",
"Type": "Integer",
"Default Value": 8778
};
data["Default Value"] = String(data["Default Value"]);
var json = JSON.stringify(data);
If you do it before you stringify the JSON you won't need to run a regex over it.
I have the following JSON variable:
var jsonObj= { "ClassA": { "A": "111", "B": "222", "C": "333", "D": "444", "E": "555", "F": "666", "G": "777" }, "ClassB": { "A":"22","B":"33","C":"44","D":"55","E":"66","F":"77","G":"AAA" }};
How do I get the class A value for key A ?
I am writing a function to allow for me to get these, something like:
function getDisplayValue(turnOverBracketCategory, classTypeAorB) {
if(classTypeAorB == "A") {
alert("1");
return jsonObj.ClassA[turnOverBracketCategory];
} else {
alert("3");
return jsonObj["ClassB"].key[turnOverBracketCategory];
}
}
Where turnOverBracketCategory is the key ("A", "B", etc.) and the classTypeAorB defines if using "ClassA" or "ClassB".
You can access ClassA + A doing this:
jsonObj.ClassA.A
will return 111
You can get the keys like this
Object.keys( jsonObj.ClassA );
will return "A","B"....
Thanks! Not exactly what I wanted, but good to know that I can also access the key. Althouh, what I am looking for is the value...
I already had the answer, the issue was that the variable was not being correctly populated.
Cheers.
To get the value I would do the following
jsonObj.ClassA[turnOverBracketCategory]
or
jsonObj.ClassA["A"]