1

I very new to programming and I can't find the solution of my issue, can you give me the solution please?

I have this JSON file:

{
  "groups": "[{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }]"
}

And I need something like this in my js (but i want import my JSON to get array like this) :

const groups = [{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }]

I don't know how to do without using jQuery.

I already tried with this:

const json = require('./test.json');

This code returns an object: screen of what is returned

It's almost what I want but it didn't work when I use it in my code because I don't want an object but and array like I said above.

How can achieve this?

Mystical
  • 2,505
  • 2
  • 24
  • 43

6 Answers6

3

The value of groups is not valid JSON: string values should be surrounded by double-quote marks, and so should keys. The file with valid JSON in that string would look like this:

{
  "groups": "[{ \"id\": 1, \"title\": \"group 1\" }, { \"id\": 2, \"title\": \"group 2\" }]"
}

Of course if you have control over the creation of this file, it would be better to have this value as part of the native JSON content, rather than JSON-in-a-string-inside-JSON. If that's not possible, you will need to correct the quoting in the string yourself, which can be done with a couple of Regular Expression replacements.

/* obj is the object in the JSON file */
var json_str = obj.groups.replace(/'/g,"\"").replace(/([a-z]+)\:/g,"\"$1\":");
var groups = JSON.parse(json_str);

Alternatively, although the string is not valid JSON it is a valid Javascript expression, so if the contents of the file are trustworthy, you can also do it with eval:

var groups = eval(obj.groups);
Headbank
  • 361
  • 2
  • 6
  • Almost, but you don't need to escape slashes or replace. Working example: https://codepen.io/anon/pen/dwjBdb – suncat100 Jan 09 '19 at 15:56
  • @suncat100 I'm not sure what you mean? Double-quotes within a single-quoted string don't need backslash-escaping, but a single-quoted string is not valid JSON, so the asker's file can't be changed in that way and still be a valid JSON file. My answer shows how to convert the string into valid JSON so it can be fed into `JSON.parse()`, or how to sidestep that requirement using `eval()`. Your example starts with an already-corrected version of the JSON string, so you are jumping ahead. – Headbank Jan 09 '19 at 18:04
  • Sure. I see now you have explained this in your post. Of course, the ultimate fix to his question is to actually fix his JSON first ... After all, the point of JSON in the first place is structuring data for code, and he added his data into a "string" instead. When structured properly, it will transmit correctly to JS with little effort. – suncat100 Jan 11 '19 at 04:50
  • The asker hasn't said whether he has control over the content of the JSON file. I'm guessing he does not, but have addressed in my answer what he can do if he does (2nd para). – Headbank Jan 11 '19 at 15:32
0

I just need to fill my array "groups" like that :

[{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }]

with a json file and without jquery

0

Since I didn't notice the "without jQuery" in the original question, here is a new answer:

var request = new XMLHttpRequest();
request.open('GET', './test.json', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    // Success!
    var data = JSON.parse(request.responseText);
  } else {
    // We reached our target server, but it returned an error

  }
};

It does two things: 1. Loads the json file 2. Parses the loaded string into a javascript object.

suncat100
  • 2,118
  • 1
  • 17
  • 22
-1

if you can't edit original text, you need replace ' to " and then did JSON.parse(json.groups);

otherwise you can change a little your json like this:

JSON.parse('[{ "id": 1, "title": "group 1" }, { "id": 2, "title": "group 2" }]')

be careful with " and ' parentheses

{
  "key":"string"
}

string with defined with ' parentheses not valid

in JSON keys must be to in "" parentheses

Vadim Hulevich
  • 1,803
  • 8
  • 17
-1

Before you can even do anything with your JSON file, you need to load it. jQuery has a shortcut, which will even automatically parse the JSON-string into a native JS object for you:

$.getJSON('./test.json', function(data) {
  console.dir(data);
});

https://api.jquery.com/jquery.getjson/

suncat100
  • 2,118
  • 1
  • 17
  • 22
  • i said without jquery ^^ – valentin marchand Jan 09 '19 at 15:04
  • Ok sorry. In either case, you need to do TWO things: 1) Load the file by Ajax (XMLHttpRequest), 2) JSON.parse(the_loaded_data). Unfortunately, without jQuery, the AJAX request is much longer. The answer is basically here: https://stackoverflow.com/questions/35294633/what-is-the-vanilla-js-version-of-jquerys-getjson There is no way around those two tasks. – suncat100 Jan 09 '19 at 15:08
-2

You can parse the object to an array this way:

Object.values(YOUR_OBJECT)

docs: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/values

nyu.exe
  • 317
  • 1
  • 9
  • This would not actually produce what OP is looking for. If `YOUR_OBJECT` is the content of the file, then you'd just get an array with a single *string* describing an array. If it's the value of the `groups` key, then it's going to produce (essentially) gibberish, as you're getting the values for all keys off a string. – VLAZ Jan 09 '19 at 14:53
  • Oh, i didn't noticed that :S – nyu.exe Jan 09 '19 at 14:58