This question already has answers here:
Parse JSON in JavaScript? [duplicate]
(16 answers)
Closed 4 years ago.
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:
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?
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);
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
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.
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/
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
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
Related
I'm creating a webpage which displays data which I have parsed from a JSON. I am using 2 JSON files. One I can parse with no problems however, the second I am struggling with.
I want to be able to parse the JSON looking for a specific object string and return all the other object strings within the same dictionary.
The layout of the JSON is:
{
"example":[
{
"Area":"Inside",
"Player":"1",
"Status":1,
"Start_Time":"2016-12-21",
"End_Time":"2016-12-22",
},
{
"Area":"Outside",
"Player":"1",
"Status":1,
"Start_Time":"2016-12-24",
"End_Time":"2016-12-25",
},
{
"Area":"Outside",
"Player":"2",
"Status":1,
"Start_Time":"2016-12-26",
"End_Time":"2016-12-28",
}
]
}
I want to say
if (player=="1") {//show ALL areas and start and end time}
//output should be something like: Area: Inside, Player: 1, Status: 1, Start_Time: 'Time', End_Time: 'Time', Area: Outside, Player: 1, Status: 1, Start_Time: 'Time', End_Time: 'Time'
I am trying to parse the JSON in javascript, this is how I am parsing the other JSON:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
var dateTime = myObj.Date;
}
};
xmlhttp.open("GET", "http://web/server/file.json", true);
xmlhttp.send();
Any help is appreciated.
You may want to try filter
myObj.example.filter(obj => obj.Player == "1")
// 0: {Area: "Inside", Player: "1", Status: 1, Start_Time: "2016-12-21", End_Time: "2016-12-22"}
// 1: {Area: "Outside", Player: "1", Status: 1, Start_Time: "2016-12-24", End_Time: "2016-12-25"}
Using forEach loop
var a={
"example":[
{
"Area":"Inside",
"Player":"1",
"Status":1,
"Start_Time":"2016-12-21",
"End_Time":"2016-12-22",
},
{
"Area":"Outside",
"Player":"1",
"Status":1,
"Start_Time":"2016-12-24",
"End_Time":"2016-12-25",
},
{
"Area":"Outside",
"Player":"2",
"Status":1,
"Start_Time":"2016-12-26",
"End_Time":"2016-12-28",
}
]
};
a.example.forEach(e=>e.Player=="1" && e.Area=="Inside"?console.log(e):false)
You really have two problems here: fetching the JSON and then parsing it to find the data you're interested in. The following snippet takes care of the first task with fetch() (the modern successor to XMLHttpRequest) and the latter task with Array.prototype.filter.
Note that if you're not using a modern javascript environment, this solution will fail. Also note that this could could be improved using the newish async/await. I excluded them for simplicity's sake.
fetch("http://web/server/file.json") // supported in modern browsers.
.then(res => res.json()) // parses into JSON. Fails if given improper json
.then(data => {
console.log(data.example.filter(el => el.Player === 1)); // filter returns an array with only elements that meet the condition
});
I want to read data from a file and add it to an Object stored in memory. The data in the file text.txt looks roughly like this:
One: {title: 'One' ,
contributor: 'Fred',
summary: 'blah' ,
comments: 'words' },
Two: {title: 'Two' ,
contributor: 'Chris' ,
summary: 'blah blah i'm a blah' ,
comments: '' },
I'm trying to set it to an empty Object like so:
var fs = require('fs');
var text = Object.create(null);
fs.readFile("./public/text.txt", "utf-8", function(error, data) {
text = { data };
});
However, when I log text to the console, it comes out looking like this:
{ data: 'One: {title: \'One\' ,\ncontributor: \'Fred\',\nsummary: \'blah\' ,\ncomments: \'words\' },\n \nTwo: {title: \'Two\' ,\ncontributor: \'Chris\' ,\nsummary: \'blah blah i\'m a blah\' ,\ncomments: \'\' },\n\n' }
Apparently, it's reading data as a key. What I really want, though, is something more like so:
{
One: {title: 'One' ,
contributor: 'Fred',
summary: 'blah' ,
comments: 'words' },
Two: {title: 'Two' ,
contributor: 'Chris' ,
summary: 'blah blah i'm a blah' ,
comments: '' },
}
Any advice here would be much appreciated.
If you are using a newer version of Node, then you have support for ES6.
// So your code
`text = { data }`
// is actually a shortcut for
`text = { data: data }`
That's why you end up with an object that has the key data and the value is a string version of what was found in the file. Instead, just use JSON.parse on the data parameter (which is a string) and it'll convert it to an Object, which you can store in text. Like this
var fs = require('fs');
var text = Object.create(null);
fs.readFile("./public/text.txt", "utf-8", function(error, data) {
text = JSON.parse(data);
});
You'll also need to make the file valid json. Which means keys need quotes around them as do String values.
{
"One": {
"title": "One" ,
"contributor": "Fred",
"summary": "blah" ,
"comments": "words"
},
"Two": {
"title": "Two" ,
"contributor": "Chris" ,
"summary": "blah blah i'm a blah" ,
"comments": ""
}
}
What you are trying to do is use eval, which is the only way if you really don't want to edit the file to be valid JSON or to export an object as #Spidy suggested. Just be sure the file is valid JavaScript, because the example you gave had
summary: 'blah blah i'm a blah'
but you need to escape i'm like i\'m.
var fs = require('fs');
var text = {};
fs.readFile('./public/text.txt', 'utf-8', function (error, data) {
eval(`text = {${data}}`);
//eval('text = {' + data + '}');
});
But I wouldn't necessarily recommend that because that allows arbitrary javascript to get executed. Depending on how the data in the file gets there it would be a huge security risk.
I'm new to Node.js. I have a JSON object which looks like the following:
var results = [
{ key: 'Name 1', value: '1' },
{ key: 'Name 2', value: '25%' },
{ key: 'Name 3', value: 'some string' },
...
];
The above object may or may not have different values. Still, I need to get them into a format that looks exactly like the following:
{"Name 1":"1","Name 2":"25%","Name 3":"some string"}
In other words, I'm looping through each key/value pair in results and adding it to a single line. From my understanding this single line approach (with double quotes) is called "JSON Event" syntax. Regardless, I have to print my JSON object out in that way into a text file. If the text file exists, I need to append to it.
I do not know how to append to a text file in Node.js. How do I append to a text file in Node.js?
Thank you!
You can use JSON.stringify to convert a JavaScript object to JSON and fs.appendFile to append the JSON string to a file.
// write all the data to the file
var fs = require('fs');
var str = JSON.stringify(results);
fs.appendFile('file.json', str, function(err) {
if(err) {
console.log('there was an error: ', err);
return;
}
console.log('data was appended to file');
});
If you want to add just one item at a time, just do
// Just pick the first element
var fs = require('fs');
var str = JSON.stringify(results[0]);
I have a json url that returns data in the format
{
"photos" : [
{
"id": 1, "image":"https://path/to/my/image/1.jpg"
},
{
"id": 2, "image":"https://path/to/my/image/2.jpg"
}
]
}
I'm using the json in a javascript function, and need to manipulate it to remove the root key. i.e. I want something that looks like
[
{
"id": 1, "image":"https://path/to/my/image/1.jpg"
},
{
"id": 2, "image":"https://path/to/my/image/2.jpg"
}
]
I've been hacking around with various approaches, and have referred to several similar posts on SO, but nothing seems to work. The following seems like it should.
var url = 'http://path/to/my/json/feed.json';
var jsonSource = $.getJSON( url );
var jsonParsed = $.parseJSON(jsonSource);
var jsonFeed = jsonParsed.photos
What am I doing wrong?
A couple of issues there.
That's invalid JSON, in two different ways. A) The : after "photos" means that it's a property initializer, but it's inside an array ([...]) when it should be inside an object ({...}). B) There are extra " characters in front of the images keys. So the first thing is to fix that.
You're trying to use the return value of $.getJSON as though it were a string containing the JSON text. But $.getJSON returns a jqXHR object. You need to give it a success callback. That callback will be called with an object graph, the JSON is automatically parsed for you.
Assuming the JSON is fixed to look like this:
{
"photos": [
{
"id": 1,
"image": "https://path/to/my/image/1.jpg"
},
{
"id": 2,
"image": "https://path/to/my/image/2.jpg"
}
]
}
Then:
$.getJSON(url, function(data) {
var photos = data.photos;
// `photos` now refers to the array of photos
});
I'm sending a JSON object to ruby with javascript. But I cannot parse it in there. I tried following stuff but no luck. Also I've been searching around for while now, but I couldn't find anything helpful.
Note that I'm very new ruby.
My trials:
def initialize(game_conf_json)
parsed_conf = JSON.parse(conf_json)
#param1 = parsed_conf['name'][0]
#param2 = parsed_conf['surname'][0]
=begin
I also tried this:
#param1 = parsed_conf['name']
#param2 = parsed_conf['surname']
But no matter what other things I try, I'm getting the following error:
"21:in `[]': can't convert String into Integer (TypeError)"
OR
"can't convert Array into String (TypeError), "
=end
File.open("some_direc/conf.json", "w") do |f|
f.write(game_conf_json)
end
end
I create the json in javascript like this:
var json_of_form_vars = {};
json_of_form_vars.name = name_val;
json_of_form_vars.surname = surname_val;
And send it this way:
$.ajax({
url: "../fundament/dispatch.rb/",
type: "post",
dataType: "json",
data: "conf="+json_of_form_vars,
.....
How can I solve this problem? Is there any proper tutorial for this of problem?
UPDATE1 (After suggestions):
I used JSON.stringify and then passed the object to ruby. And then I finally able to print the object in ruby. It's listed below:
{"name": "METIN", "surname": "EMENULLAHI"}
The method .class claims that it is an array. But I cannot access data with classical ways, like:
array['name']
the error is:
can't convert String into Integer
And when I try to pass it to the JSON.parse in ruby, it gives me the following error:
can't convert Array into String
So I used JSON.parse(conf_array.to_json), but again when accessing the data it gives the same error like arrays:
can't convert String into Integer
What should be done now?
UPDATE2
Here is my cgi handler which passes the URL parameters to appropriate places:
cgi_req = CGI::new
puts cgi_req.header
params_from_request = cgi_req.params
logger.error "#{params_from_request}"
action_todo = params_from_request['action'][0].chomp
base = Base.new
if action_todo.eql?('create')
conf_json = params_from_request['conf']
# This line prints the json like this: {"name": "SOME_NAME", "surname": "SOME_SURNAME"}
logger.error "#{conf_json}"
base.create_ident(conf_json)
end
And in Base class:
def create_ident(conf_json)
require 'src/IdentityCreation'
iden_create = IdentityCreation.new(conf_json)
end
IdentityCreation's constructor is listed above.
UPDATE3:
Ok, I now get at least something out of the array. But when I access a key, it displays the key itself:
parsed_conf = JSON.parse(conf_json.to_json)
#param1 = parsed_conf[0]['name']
#param2 = parsed_conf[0]['surname']
# At this point when I print the #param1, it gives me "name"(the key), not "SOME_NAME"(the value).
Here an example of parsing a JSON string. If you still have problems, publish the generated JSON so that we can try it.
require 'json'
require 'ap'
string = %{
{"configurations" : [
{ "drinks" : [
{"menus" : [
{ "hot" : [
{"id":15,"unit":"0.33", "price":"1", "currency":"Euro", "position": 4},
{"id":15,"unit":"0.33", "price":"1", "currency":"Euro", "position": 6}
] },
{ "cold" : [
{"id":15,"unit":"0.33", "price":"1", "currency":"Euro", "position": 4},
{"id":15,"unit":"0.33", "price":"1", "currency":"Euro", "position": 6}
] },
{ "terminals" : { "id" : 4, "id": 6, "id": 7 } },
{ "keys" : { "debit" : "on", "credit": "off" } }
] }
] } ] }
}
hash = JSON.parse(string)
ap hash
gives
{
"configurations" => [
[0] {
"drinks" => [
[0] {
"menus" => [
[0] {
"hot" => [
[0] {
"id" => 15,
"unit" => "0.33",
"price" => "1",
"currency" => "Euro",
"position" => 4
},
etc..
At the moment you're not actually posting json. You're attemping to post json wrapped inside form encoded parameters. In addition, when you do
"conf=" + json_of_form_vars
javascript will convert json_of_form_vars to a string for you but that conversion isn't the same as dumping to JSON. Javascript default string conversions are pretty useless for objects, so you'll need to use JSON.stringify to get actual json.
Since you're composing the body as a string literal you'll also need to escape any special characters that aren't allowed (or have special meaning) in this context. It's usually easier to let jquery do the heavy lifting, with something like
$.ajax({
url: "../fundament/dispatch.rb/",
type: "post",
dataType: "json",
data: {conf: JSON.stringify(json_of_form_vars)}
I solved it finally. Using all the suggestions made under this post and also my irb experiences with hashes, arrays, json and etc.
So instead of converting my object (conf_json) to json (with to_json), I passed it to JSON.parse as a string like below:
parsed_conf = JSON.parse(%{#{conf_json}})
It seems kind of weird to me, because when try to pass it to function like below, I got the error of can't convert Array into String.
parsed_conf = JSON.parse(conf_json)
But it is working like a charm right now.