How to add the new JSON from existing JSON file - javascript

I searched here get few related posts found but not helpful. I created one json file it has some text i want to append some more json in that using javascript(JSON stored in locally).
I have json file like this:
{ "Home": [ "a", "b", "c" ] }
i want to include this text "Log": 1
want to achieve like this,
{ "Home": [ "a", "b", "c" ], "Log": 1 }
Now I have like this in my json file(currently i have but json format is not correct)
{ "Home": [ "a", "b", "c" ] }
{ "Log": 1 }
$.getJSON('myfile.json', function(data) {
alert("success");
}.error(function(data){
alert(JSON.stringify(data));
});
this returns parser error. I know the JSON format is wrong. Please guide me to create a correct JSON format.

The error is in both versions of the JSON. You are missing the " at the start of the string c.
http://jsonlint.com/ will help you track down where errors in JSON occur.
As a rule of thumb, you should create JSON using a JSON serializer in a mature library and not by hand or string concatenation.
Now i have like this in my json file
That's completely wrong. The code you had in "Now i want to achieve like this" was right (aside from the error mentioned above).

You need to read your JSON, parse it into a JS object, edit the object, and convert back into JSON before writing:
assuming myfile.json contains:
{ "Home": [ "a", "b", "c" ] }
$.getJSON('myfile.json', function(data) {
alert("success");
obj = JSON.parse(data);
obj.log = 1;
writeJSON(JSON.stringify(obj));
}.error(function(data){
alert(JSON.stringify(data));
});
and writeJSON will be something like:
function writeJSON(jsonString)
$.ajax({
type: 'POST',
url: 'myfile.json',
data: jsonString,
success: function(data) { alert('write succesful!'); },
contentType: "application/json",
dataType: 'json'
});
}
assuming that you are using a server which can both read and write via this endpoint.

Related

Can't get Data from json object

I have this script:
<script type="text/javascript">
function requestimg(username){
$.ajax({
url: '{% url "image" %}',
data: {
'username': username
},
dataType: 'json',
success: function (data) {
if (data) {
//Printing the whole data
console.log(data);
//Printing to see where I am
console.log("Name: ");
//Trying to rint the name
console.log(data[0].nombre);
}else {
alert("May Day");
}
}
});
}
I have a problem reading the properties in the json object
When i print the data I get this:
{
json: "[
{
"model": "polls.imagen",
"pk": 17,
"fields": {
"n…"36",
"imagen": "polls/static/pictures/dr.jpg"
}
}
]"
}
And when i print the data as I have it on the code i get:
Uncaught TypeError: Cannot read property 'nombre' of undefined
I have tryied writing it like data.nombre but i just get undefined
I have also tried this console.log(data[0].fields); , data[0].model, data.model
IMPORTANT I want to clarify that i wont know why there are 2 json objects im supposed to get just one and even if i try to put a [1] instead of the [0] i get the same mistakes.
I've tried answers from some previous similar questions and they didn't help.
You will be able to access the fields per
data.json[0].fields
the response of your url is an array, named json
Additionally data.json is returning a string, so convert it to JSON with
data.json = JSON.parse(data.json);
Convert it to JSON first JSON.parse(data.json)
This will give you the access to the fields object data.json[0].fields

Value showing undefined when trying to output data returned as json from server

I am new to Yii2 framework and PHP.I used Mongo DB as the backend database.I fetched a document from a collection and returned the data as Json from the controller.The data returned back is given below.
{
"55b08c383e1a36233fdbdc06": {
"_id": { "$id": "55b08c383e1a36233fdbdc06" },
"address": [ "abcdgt", "zxcv" ],
"age": "23",
"email": [ "qwert#gmail.com","abcd#mail.com" ],
"location": "kollam",
"name": "ajiths",
"phoneno": [ "9522585456", "7875642256" ] ,
"sex": "male"
}
}
But I am getting 'Undefined' when trying to alert result.name in Javascript code.The code at the front end is given below.
function loadClient(id){
url = "<?= Yii::getAlias('#serverpathweb')?>/client/showclient?id="+id;
$.ajax({
url: url ,
method: "GET",
success: function(result){
alert(result.name);
}
});
}
The code at the controller end is given below.
public function actionShowclient($id) {
$clientdetail = Yii::$app->mongodb->getCollection('client');
$result = $clientdetail->find(["_id" =>$id]);
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $result;
}
Can anyone tell me how to get the value result.name.
your getting JSON result with id as key so access ur JSON data like this
first get the key of ur JSON using Object.keys
next using key print the values you need
var id=Object.keys(result)[0]; //it will print your JSON key i.e. "55b08c383e1a36233fdbdc06"
alert(result[id]['name']); // it will print the name
Note if you are getting multiple user details please let me know
Your "result" object is probably a String because you're not telling jQuery otherwise. Trying adding the option dataType:json to your request as in:
$.ajax({ url: url, method: 'GET', dataType: 'json', etc...
Edit: It also looks like there's a simple bug in your code. You need to access your property where it's nested in the resulting object:
result[id].name

Scraping JSON data from an AJAX request

I have a PHP function that echoes out JSON data and pagination links. The data looks exactly like this.
[{"name":"John Doe","favourite":"cupcakes"},{"name":"Jane Citizen","favourite":"Baked beans"}]
Previous
Next
To get these data, I would use jQuery.ajax() function. My code are as follow:-
function loadData(page){
$.ajax
({
type: "POST",
url: "http://sandbox.dev/favourite/test",
data: "page="+page,
success: function(msg)
{
$("#area").ajaxComplete(function(event, request, settings)
{
$("#area").html(msg);
});
}
});
}
Using jQuery, is there anyway I can scrape the data returned from the AJAX request and use the JSON data? Or is there a better way of doing this? I'm just experimenting and would like to paginate JSON data.
It's better to not invent your own formats (like adding HTML links after JSON) for such things. JSON is already capable of holding any structure you need. For example you may use the following form:
{
"data": [
{"name": "John Doe", "favourite": "cupcakes"},
{"name": "Jane Citizen", "favourite": "Baked beans"}
],
"pagination": {
"prev": "previous page URL",
"next": "next page URL"
}
}
On client-side it can be parsed very easily:
$.ajax({
url: "URL",
dataType:'json',
success: function(resp) {
// use resp.data and resp.pagination here
}
});
Instead of scraping the JSON data i'd suggest you to return pure JSON data. As per your use case I don't think its necessary to write the Previous and Next. I am guessing that the first object in your return url is for Previous and the next one is for Next. Simply return the below string...
[{"name":"John Doe","favourite":"cupcakes"},{"name":"Jane Citizen","favourite":"Baked beans"}]
and read it as under.
function loadData(page){
$.ajax
({
type: "POST",
url: "http://sandbox.dev/favourite/test",
dataType:'json',
success: function(msg)
{
var previous = msg[0]; //This will give u your previous object and
var next = msg[1]; //this will give you your next object
//You can use prev and next here.
//$("#area").ajaxComplete(function(event, request, settings)
//{
// $("#area").html(msg);
//});
}
});
}
This way return only that data that's going to change not the entire html.
put a dataType to your ajax request to receive a json object or you will receive a string.
if you put "previous" and "next" in your json..that will be invalid.
function loadData(page){
$.ajax({
type: "POST",
url: "http://sandbox.dev/favourite/test",
data: {'page':page},
dataType:'json',
success: function(msg){
if(typeof (msg) == 'object'){
// do something...
}else{
alert('invalid json');
}
},
complete:function(){
//do something
}
});
}
and .. in your php file, put a header
header("Content-type:application/json");
// print your json..
To see your json object... use console.log , like this:
// your ajax....
success:(msg){
if( window.console ) console.dir( typeof(msg), msg);
}
Change your json to something like this: (Use jsonlint to validate it - http://jsonlint.com/)
{
"paginate": {
"previous": "http...previsouslink",
"next": "http...nextlink"
},
"data": [
{
"name": "JohnDoe",
"favourite": "cupcakes"
},
{
"name": "JaneCitizen",
"favourite": "Bakedbeans"
}
]
}
You can try this :-
var jsObject = JSON.parse(your_data);
data = JSON.parse(gvalues);
var result = data.key;
var result1 = data.values[0];

accessing json data from jquery

I'm creating an ajax app using jQuery 1.4.2 and I've tried using using get(), post() and the ajax() method itself. My php service returns:
[{"k":"label0","v":0.5},{"k":"label1","v":99.43},{"k":"label2","v":2.46},{"k":"label3","v":46.29},{"status":"OK"}]
in my success callback I have tried accessing as json.status and json[0][0]
but it always returns "undefined". what am I doing wrong?
function getSysinfo(source) {
var json = null;
$.ajax({
url: source,
type: 'POST',
dataType: 'json',
success: function (data) {
json = eval("(" + data + ")");
$('#data').html(json.status);
alert(json[0][0]);
refreshChart(json);
},
error: function (request, status, error) {
alert("REQUEST:\t" + request + "\nSTATUS:\t" + status +
"\nERROR:\t" + error);
}
});
return json;
}
I've been googling this for days. How the heck do I access the returned data? any help would be appreciated.
To access that status value you would need:
data[4].status
This is because it is an object stored in the the fifth element in an array, with status being a property on the object.
Your JSON-data looks like this:
[
{
"k": "label0",
"v": 0.5
},
{
"k": "label1",
"v": 99.43
},
{
"k": "label2",
"v": 2.46
},
{
"k": "label3",
"v": 46.29
},
{
"status": "OK"
}
]
You would have to read your status using
json[4].status
with the 4 as a magical number or length-1 - not desirable. I would consider modifying your servers response to something more useful like this:
{
"status": "OK",
"entries": [ ... ] // add your data here
}
In your success callback try:
var parsed = $.parseJSON(data);
$.each(parsed, function (i, jsondata) {
alert( jsondata.k );
alert( jsondata.v );
});
You don't need the eval("("+data+")");. jQuery is automatically parsing the JSON response for you because you specified dataType:'json'
From the jQuery docs for dataType:
"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
no need to use eval any more use below code which can be more for json
$.getJSON(url+query,function(json){
$.each(json,function(i,value){
});
});
nategood already wrote that you don't need do do anything with data, it's already an object.
In this case it's an array, if you like to access the status, you need to retrieve it from the last item of the data-array(that's where you'll find it in this array):
data[data.length-1].status
But maybe you should think about another structure of your JSON, it doesn't look very comfortable.
Something like that:
{
"items":[
{"k":"label0","v":0.5},
{"k":"label1","v":99.43},
{"k":"label2","v":2.46},
{"k":"label3","v":46.29}
],
"status":"OK"
}
...should be easier to handle, because you can simply access data.status instead of first looking where you may find it inside the response(what may be error-prone ).
The data parameter is the decoded JSON as you can see in this example:
http://www.jsfiddle.net/rLprV/1/
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: formData,
showLoader:true,
success: function (response) {
var parsed = JSON.parse(JSON.stringify(response));
$.each(parsed, function (key, val) {
alert( val.name );
});
},
error: function (err) {
alert("Please enter a valid id")
}
});

Parsing JSON array in JQuery

I'm trying to get the hand on JQuery and JSON using an ASP.NET webservice. The Webservice returns this result:
{
MyResult: {
Ticket: {
"Author": "rd",
"CssClass": "RED",
"ExpirationDateTime": "2009-08-16T16:55:43.577+02:00",
"id": "38",
"Message": "We are going down",
"ModifiedDateTime": "2009-08-17T11:14:20.5+02:00",
"MoreInfo": null
}
}
}
On the client side I'm using JQuery to get the result using the ajax function like this:
$.ajax({
type: "POST",
url: "TickerFeeder.asmx/GetTicket",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(resultJSON) {
//-- Please fill your code here for getting the first item from the array into variables
}
But I'm missing out the stuff how to retrieve the first item from the JSON array into some variables. Something like this (pseudo-code):
var message = resultJSON[0].Message
var cssclass = resultJSON[0].CssClass
Anybody with a hint,help?
Thanks for your help
Cheers
Frank
Your JSON is not valid, you should use quotes on the MyResult and Ticket members.
{
"MyResult": {
"Ticket": {
"Author": "rd",
"CssClass": "RED",
"ExpirationDateTime": "2009-08-16T16:55:43.577+02:00",
"id": "38",
"Message": "We are going down",
"ModifiedDateTime": "2009-08-17T11:14:20.5+02:00",
"MoreInfo": null
}
}
}
Also there is no array involved, the arrays are defined with the square bracket characters [....] literal notation, so you can access your values directly:
resultJSON.MyResult.Ticket.Message;
resultJSON.MyResult.Ticket.CssClass;
Ok, found out that my Asp.Net webService was producing a wrong result set. So instead of returning a string item I returned a complete object and handled the Json conversion to Asp.Net webservice. That did the trick !

Categories