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
});
Related
I was given an existing project where the data structure is below:
[
{
"key": "username",
"value": ""
},
{
"key": "password",
"value": ""
},
{
"key": "cars",
"value": [
{"ABC-1234-1234": "s4LmoNzee9Xr6f7uu/"},
{"ABC-5678-5678": "s5LmoNzee9Xr5f9uu/"}
]
}
]
Cars' value is an array of objects.
To create the initial object in the cars' array, I do the following:
var encryptedStuff = json.data;
var carkey = carid;
var entry = {};
entry[carkey] = encryptedStuff;
var carArray = [];
key="cars";
carArray.push(entry);
I need to push the array into another function that turns it into a string in a stored variable.
My problem...and I'm really rusty on embedded objects...is to do the following:
1.) Get the string
2.) JSON.parse back into an object (I got this far as I'm using a jQuery grep but I'd prefer to use JavaScript).
Here's my problem...
3.) locate the cars key in the object and get its value.
4.) Turn the value into an array to either delete an item or to add one (as per the code above where I'm writing the object into the array.
In the case of adding, I would have to copy the cars' value into the carArray[] and then push the new item into it.
In the case of deleting, I would have to remove the item and push back everything back into the carArray[].
I would do things differently but I can't change the structure of the data as this is approved company-wide.
Any help would be appreciated.
Thanks
You don't need to make a copy of the car's value array to add new entries nor make a copy then "push back" to remove an entry - you can reference it directly in the parsed object.
You can use
JSON.parse
array.find
array.push
array.splice
JSON.stringify
Giving:
var source = `[
{
"key": "username",
"value": ""
},
{
"key": "password",
"value": ""
},
{
"key": "cars",
"value": [
{"ABC-1234-1234": "s4LmoNzee9Xr6f7uu/"},
{"ABC-5678-5678": "s5LmoNzee9Xr5f9uu/"}
]
}
]`
// convert json to an object
var data = JSON.parse(source);
console.log(data, data.find(e=>e.key=="cars").value)
// add an item to the cars.value
data.find(e=>e.key=="cars").value.push({"ABC-": "s6..." });
// remove an item from the cars.value
data.find(e=>e.key=="cars").value.splice(1,1);
// confirm items added/removed
console.log(data, data.find(e=>e.key=="cars").value)
// convert back to a strng to send back to the service
var result = JSON.stringify(data);
console.log(result);
Right, so I am trying to wrap my head around editing (appending data) to a JSON file.
The file (users.json) looks like this:
{
"users": {
"id": "0123456789",
"name": "GeirAndersen"
}
}
Now I want to add users to this file, and retain the formatting, which is where I can't seem to get going. I have spent numerous hours now trying, reading, trying again... But no matter what, I can't get the result I want.
In my .js file, I get the data from the json file like this:
const fs = require('fs').promises;
let data = await fs.readFile('./test.json', 'utf-8');
let users = JSON.parse(data);
console.log(JSON.stringify(users.users, null, 2));
This console log shows the contents like it should:
{
"id": "0123456789",
"name": "GeirAndersen"
}
Just to test, I have defined a new user directly in the code, like this:
let newUser = {
"id": '852852852',
"name": 'GeirTrippleAlt'
};
console.log(JSON.stringify(newUser, null, 2));
This console log also shows the data like this:
{
"id": "852852852",
"name": "GeirTrippleAlt"
}
All nice and good this far, BUT now I want to join this last one to users.users and I just can't figure out how to do this correctly. I have tried so many version and iterations, I can't remember them all.
Last tried:
users.users += newUser;
users.users = JSON.parse(JSON.stringify(users.users, null, 2));
console.log(JSON.parse(JSON.stringify(users.users, null, 2)));
console.log(users.users);
Both those console logs the same thing:
[object Object][object Object]
What I want to achieve is: I want to end up with:
{
"users": {
"id": "0123456789",
"name": "GeirAndersen"
},
{
"id": "852852852",
"name": "GeirTrippleAlt"
}
}
When I get this far, I am going to write back to the .json file, but that part isn't an issue.
That's not really a valid data structure, as you're trying to add another object to an object without giving that value a key.
I think what you're really looking for is for 'users' to be an array of users.
{
"users": [
{
"id": "0123456789",
"name": "GeirAndersen"
},
{
"id": "852852852",
"name": "GeirTrippleAlt"
}
]
}
You can easily create an array in JS and the push() new items into your array. You JSON.stringify() that with no issue.
const myValue = {
users: []
};
const newUser = {
'id': '0123456789',
'name': "GeirAndersen'
};
myValue.users.push(newUser);
const strigified = JSON.stringify(myValue);
I am writing to a json file in casperjs and am trying to add new objects to it.
json file looks like
{ "visited": [
{
"id": "258b5ee8-9538-4480-8109-58afe741dc2f",
"url": "https://................"
},
{
"id": "5304de97-a970-48f2-9d3b-a750bad5416c",
"url": "https://.............."
},
{
"id": "0fc7a072-7e94-46d6-b38c-9c7aedbdaded",
"url": "https://................."
}]}
The code to add to the array is
var data;
if (fs.isFile(FILENAME)) {
data = fs.read(FILENAME);
} else {
data = JSON.stringify({ 'visited': [] });
}
var json = JSON.parse(data);
json.visited.push(visiteddata);
data = JSON.stringify(json, null, '\n');
fs.write(FILENAME, data, "a");
This is starting off by adding an new { "visited" : [ ] } array with first couple of objects, below the existing { "visited" : [ ] } array and subsequently the script breaks because the json array is no longer valid json.
Can anybody point me in the right direction. Thank you in advance.
You have a JSON file containing some data.
You:
Read that data
Modify that data
Append the modified version of that data to the original file
This means the file now has the original data and then, immediately after it, a near identical copy with a little bit added.
You don't need the original. You only need the new version.
You need to write to the file instead of appending to it.
Change the 'a' flag to 'w'.
Have got a json file exported from mysql. One particular line is not a well represented json object, i'm trying to convert this to a proper array of object.
var data = "{"54":
{"ID":"54",
"QTY":"1",
"NAME":"Large",
"TOTAL":1.86
},
"TOTAL":10.54,
"313":
{"ID":"313",
"QTY":2,
"NAME":"Quater Pounder",
"TOTAL":8.68
}
}"
//and wants to make it:
var data = [
{"ID" : "54",
"QTY" : "1",
"NAME": "Quarter Pounder",
"TOTAL": 8.68
},
{"ID":"313",
"QTY":2,
"NAME": "Quater Pounder",
"TOTAL":8.68
}
]
I was able to fix this by using angular.forEach(response, function(item){}), I then created a childArray, which I pushed the result of the above into.
Please see code:
angular.forEach( $scope.response, function (item) {
item.childrenList = [];
angular.forEach( JSON.parse( item.details ), function (value, id) {
item.childrenList.push( value );
})
});
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.