0

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?

Jordan Micle
  • 59
  • 1
  • 8
  • I found the solution. https://stackoverflow.com/questions/14528385/how-to-convert-json-object-to-javascript-array This really helped me. Thanks – Jordan Micle Jan 30 '20 at 03:34

3 Answers3

3
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.

Simeon Ikudabo
  • 2,152
  • 1
  • 10
  • 27
0

I'm guessing the problem is the last comma:

{
  "1": "a",
  "2": "b",
  "3": "c",//<===
}

JSON doesn't allow trailing commas.

machineghost
  • 33,529
  • 30
  • 159
  • 234
0
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.

許雅婷
  • 154
  • 1
  • 6