Actionscript: Invalid JSON parse input for what seems valid - json

I have the following JSON
{
"extras": {
"google.sent_time": 1502027522898,
"custom": "{\"a\":{\"message_data\":\"\",\"message_id\":\"749\",\"message_command\":\"MESSAGE\"},\"i\":\"899ec3dd\"}",
"from": "62572096498",
"alert": "Read More...",
"title": "New message",
"google.message_id": "0:2905559%2ecccafd7ecd"
}
}
Using
var jsonObj:Object = JSON.parse(str);
Gives the error:
SyntaxError: Error #1132: Invalid JSON parse input.
at JSON$/parseCore()
at JSON$/parse()
I do not understand why this is, the JSON is valid.
Additional information,
The solution I have tried and works is as follows, despite the before and after been valid.
var clean:String = str.split("\\").join('');
clean = clean.replace('"custom":"{"a"', '"custom":{"a"');
clean = clean.replace('"}","from"', '"},"from"');

Few observations :
The JSON provide in OP is looking like a JSON object instead of JSON string.Hence, No need to parse the whole object.
As partialJsonObj.extras.custom is a JSON string parse it to convert into JSON Object.
DEMO
var partialJsonObj = {
"extras": {
"google.sent_time": 1502027522898,
"custom": "{\"a\":{\"message_data\":\"\",\"message_id\":\"749\",\"message_command\":\"MESSAGE\"},\"i\":\"899ec3dd\"}",
"from": "62572096498",
"alert": "Read More...",
"title": "New message",
"google.message_id": "0:2905559%2ecccafd7ecd"
}
};
partialJsonObj.extras.custom = JSON.parse(partialJsonObj.extras.custom);
var jsonObj:Object = partialJsonObj;
console.log(jsonObj);

If this "JSON" is part of your actionscript it's an Object, not a JSON.
The JSON.parse method won't work because accepts JSON-formatted String as first parameter and you pass and Object instead.
If you load/import this script from a JSON file, the JSON.parse method will work.
// importing the external JSON file
function loadJSON() {
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, decodeJSON);
loader.load(new URLRequest("test.json"));
}
// converting to actionscript Object
function decodeJSON(e:Event):void {
var loader:URLLoader = URLLoader(e.target) ;
var jsonObj:Object = JSON.parse(loader.data);
trace(jsonObj["extras"]["custom"]["a"]["message_id"]);
}
loadJSON();
If you want to access the "custom" value, uncomment double quotes in the JSON file:
"custom": {"a":{"message_data":"","message_id":"749","message_command":"MESSAGE"},"i":"899ec3dd"},

I believe str is a javascript object already, so nothing to parse and you can simply assign it like:
var jsonObj:Object = str;
However I'd assume you need to parse and convert to object your custom property:
a.extras.custom = JSON.parse("{\"a\":{\"message_data\":\"\",\"message_id\":\"749\",\"message_command\":\"MESSAGE\"},\"i\":\"899ec3dd\"}")

Related

Parsing JSON in Google Scripts

I am trying to parse a JSON object in Google Scripts but I can't seem to get it to work.
The JSON I am trying to parse looks like this
{
"keywords":[
{
"c":0.015165274822976534,
"monthly":[ ],
"kw":"handstand",
"n":60500,
"sb":0.3
}
],
"not_found":[
]
}
I can't seem to access any of the values within the object. If I use JSON.parse() it seems to create a non-JSON object.
var response = '{"keywords":[{"c":0.015165274822976534,"monthly":[
],"kw":"handstand","n":60500,"sb":0.3}],"not_found":[]}'
var obj = JSON.parse(response);
Logger.log(obj);
Returns
{keywords=[{c=0.015165274822976534, monthly=[], kw=handstand, n=60500, sb=0.3}], not_found=[]}
This doesn't validate.
If I try to work with that anyways this happens
var response = '{"keywords":[{"c":0.015165274822976534,"monthly":[
],"kw":"handstand","n":60500,"sb":0.3}],"not_found":[]}'
var obj = JSON.parse(response);
Logger.log(obj.keywords.n)
Returns undefined
If I don't use JSON.parse and just work with the original response object I get the following:
var response = '{"keywords":[{"c":0.015165274822976534,"monthly":[ ],"kw":"handstand","n":60500,"sb":0.3}],"not_found":[]}'
Logger.log(response.keywords);
I get undefined
I'm not really sure where I am going wrong here. Any help is appreciated. Thanks!
As #Tanaike mentions, your n property is a property of an object in the keywords array. So to log the values of n, you need to - after parsing the string to JSON - evaluate each object in keywords:
var response = '{"keywords":[{"c": 0.015165274822976534, "monthly": [ ], "kw": "handstand", "n": 60500, "sb": 0.3}], "not_found": []}'
var obj = JSON.parse(response);
// Log all values of n for each keyword:
obj.keywords.forEach(function (keyword) {
console.log("Word: " + keyword.kw + ", times used: " + keyword.n);
});

How to updateItem for Map dataType in dynamoDB

I am trying to use Map datatype in dynamodb to insert my JSON object. The JSON I am getting from external API is bit long and got nested Array of objects in it. (I am using nodejs.)
{
"a": "foo",
"b": "foo1",
"c": [{
"boo": 10,
"boo1": 15
}, {
"boo": 19,
"boo1": 45
}, {
"boo": 11,
"boo1": 25
}]
}
From the research i made so far it looks like i have to specify types for every single element in the json i am trying to insert/update. It make it harder since in my case the json could have anything.
If anyone experienced the same issue and know any solution for it please let me know.
You need to specify the exact types for every value only if you use the low-level AmazonDB API.
But you can use an AWS SDK which makes things much easier and you can use the json notation directly.
I didn't use node.js SDK (have experience with python SDK), but looking at the examples, this is true for node.js too.
Check this one:
var AWS = require("aws-sdk");
AWS.config.update({
region: "us-west-2",
endpoint: "http://localhost:8000"
});
var docClient = new AWS.DynamoDB.DocumentClient();
var table = "Movies";
var year = 2015;
var title = "The Big New Movie";
var params = {
TableName:table,
Item:{
"year": year,
"title": title,
"info":{
"plot":"Something happens."
}
}
};
console.log("Adding a new item...");
docClient.put(params, function(err, data) {
if (err) {
console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
} else {
console.log("Added item:", JSON.stringify(data, null, 2));
}
});
Here the Item inside the params passed into the docClient.put call is just a plain javascript object.
It's necessary for dynamodb to know what type of data your are inserting/updating. So dynamodb or any db allows only
datatype that is specific to that column. If you looking to parse json(with Jackson api) to specific type and insert. Below is the code
JsonParser parser = new JsonFactory().createParser(new File(
"target/resources/json_file.json"));
JsonNode rootNode = new ObjectMapper().readTree(parser);
Iterator<JsonNode> iter = rootNode.iterator();
ObjectNode currentNode;
while (iter.hasNext()) {
currentNode = (ObjectNode) iter.next();
table.putItem(new Item().withPrimaryKey("a", currentNode.path("a").asText(), "b",
currentNode.path("b").asText()).withJSON("c",currentNode.path("c").toString()));
}

How to post into the MongoDb collection using postman

I am trying to insert data into the MongoDb collection using postman. How would I approach this; hardcoding the data in JSON format works, but I want to be able to insert using postman in JSON format.
This is the code that allowed me to enter directly, using the post function in postman, with no input:
public async void Insert([FromBody]string value)
{
var client = new MongoClient();
var dbs = client.GetDatabase("test");
var collection = dbs.GetCollection<BsonDocument> ("restaurants");
BsonArray dataFields = new BsonArray { new BsonDocument {
{ "ID" , ObjectId.GenerateNewId()}, { "_id", ""}, } };
var document = new BsonDocument
{
{"borough",value },
{"cuisine","Korean"},
{"name","Bellaa"},
{"restaurant_id","143155"}
};
await collection.InsertOneAsync(document);
}
You can send it as raw data. You will set the post type to application/json.
This comes From the docs.

How to read JSON file in phonegap?

I am using phonegap here.But how to read JSON file ??
function readAsText(file) {
var reader = new FileReader();
alert("inside readAstext");
var jsonArray;
reader.onloadend = function(evt) {
displayContents = evt.target.result;
alert("assigned");alert(displayContents);
jsonArray = JSON.parse(displayContents);
}
reader.readAsText(file);
handleResponse(true,jsonArray);
}
here evt.target.result is displaying my file in alert as a sting . But once i parse that file I am getting [object object] once inside for loop. How to parse this ? Am i wrong?how to read each content of json here?
When you parse a JSON file, you convert it onto an objects, hence your 'alert' is correct. Now that you have an object, simply retrieve the values from the object's properties.

Why eval() isn't working here to deserialize such a simple JSON object?

I am trying to use eval() function to deserialize this JSON text by using eval function.
var personJSON = {
"FirstName": "Burak",
"LastName": "Ozdogan",
"Id": "001",
"Department": "Information Technologies"
};
var personBurakOzdogan = eval('(' + personJSON + ')');
But I am getting this error:
*Microsoft JScript compilation error: Expected ']'*
Is there something that I skip which I cannot catch?
Thanks
What you have is not JSON text. It is already a JSON object. So you don't need to use eval at all. You can directly access and manipulate its properties:
alert(personJSON.FirstName);
Try to check if your personJSON is a wrapper that CONTAINS the real json. For example, try to write:
var person = eval('(' + personJSON.Person + ')')
where Person is the class serialized by the service.
OR
try this:
var person = eval('(' + personJSON.GetPersonResult + ')')
where GetPerson is the method name in the service, plus Result.
you are not dealing with a string, but with a json object. You are trying to evaluate a json object as string to create a json object.
var personJSON =
'{"FirstName":"Burak","LastName":"Ozdogan","Id":"001","Department":"Information Technologies"}';
var personBurakOzdogan = eval('(' + personJSON + ')');
this should work, although it doesn't make to much sense. this makes more sense:
var personBurakOzdogan = {
"FirstName": "Burak",
"LastName": "Ozdogan",
"Id": "001",
"Department": "Information Technologies"
};
You have to pass to the variable a string type as the code seen below:
var personJSON = '{"FirstName":"Burak","LastName":"Ozdogan","Id":"001","Department":"Information Technologies"}';