I've found that I can't use the standard JSON string in the Cypher query while I were writing a Node.js application:
var neo4j = require('neo4j')
,db = new neo4j.GraphDatabase('http://localhost:7474')
,enc_datum = JSON.stringify({id: 1, data: 'foo'})
,qstr = ['MATCH (n %DATUM)'
,'RETURN n'
].join('\n')
.replace('%DATUM', enc_datum)
db.query(qstr)
It would complain about the '"' character, because Cypher accept encoded object like this:
MATCH (n {id: 1, data: 'foo'})
RETURN n
Which is not what encoded with JSON:
var enc_datum = JSON.stringify({id: 1, data: 'foo'})
console.log(enc_datum)
// would be {"id":1,"data":"foo"}
The error messages show that Cypher, or the Neo4j module, doesn't accpet standard JSON because of the " character. It would complain that the next character after the { should be identifier or something else.
So I got stuck: either I must handle the JSON string with some nasty RegExpr before it got embedded in the query string, or I must invent a way to encode objects just for the tiny " character. I just want to ask if there're some more suitable solutions before I jump into these two tricky ways...
(I now solve this in test by using eval instead of JSON to eval my encoded data, while the string would be directly used in the Cypher query so I can't use JSON to stringify it. But I can't handle client encoded JSON in this way)
MATCH (n {id: 1, data: 'foo'})
The format you seem to be using is JSON5. You can avoid double quotes with code like this:
var jju = require('jju')
jju.stringify({id: 1, data: 'foo'}, {quote:"'"}).replace(/"/g,'\\x22')
// result: "{id: 1, data: 'foo'}" (string)
jju.parse("{id: 1, data: 'foo'}")
// result: {id: 1, data: 'foo'} (object)
Please note two important things here:
"quote" parameter ensures that module will always use single quotes to wrap strings
replace() ensures that all double quotes will be encoded as \x22 if they happen to be in your input (i.e. data: 'foo"bar')
I don't know what other restrictions do that database have, maybe it's worth to encode it with base64 or something.
Cypher doesn't use JSON it is a map format that looks a bit like JSON but doesn't use quotes for keys
use parameters instead MATCH (n {props}) pass the actual parameters as values
like this
{"query","MATCH (n {props}) return n",
"params": {"props":{"id":1,"data":"foo"}}}
Related
... I am experiencing an anomaly that I do not understand why.
The scenario is as follows:
1.- From JSP, using JS, I send data in JSON format to a servlet.
JSON: "{'ORDER': '1', 'DATE': '06-01-2018', 'TIME': '07:06:51', 'BOUCHER': '208896.0', 'LIC' : 'HSGR30', 'QTY': '0.0'} "
2.- I capture the data, with the getParameter utility, on a String type variable.
3.- I pass the variable to the JSONObject utility, and it does not process it since there are two "" (two double quotes) in that variable, and debugging the class (JSONObject) throws an exception because the first character of the string is not "{" ... which is logical.
4.- Now, if I take the complete stream and paste it in the call:
JSONObject obj = new JSONObject ("{'ORDER': '1', 'DATE': '06-01-2018', 'TIME': '07:06:51', 'BOUCHER': '208896.0' , 'LIC': 'HSGR30', 'QTY': '0.0'} ")
It processes it correctly and I get the object with its associated properties and values.
I was considering that the JSON format I send from JS is not valid???. But I can't find the cause of why???
The problem is that I don't understand why two double quotes appear.
If you can give me a hand with this,
thank you very much !!!
use double quotes: " instead of single quotes: ' and use \ before each doublquote to escape the characters.
E.g:
JSONObject obj = new JSONObject ("{\"ORDER\": \"1\",\"DATE\": \"06-01-2018\",\"TIME\": \"07: 06: 51\",\"BOUCHER\": \"208896.0\",\"LIC\": \"HSGR30\",\"QTY\": \"0.0\"}");
Very grateful for your prompt replies.
I found the problem, in the js code I was doing JSON.stringify(). I remove it and everything is fine.
I just need to rethink how to send, from js, package JSON formatted records.
It was not clear how JSONObject handles the string it receives.
I guess I'll have to rethink an array of JSON objects and then send it. Perhaps, by receiving array object type, it will understand that it is a batch of records.
Thanks again
I use basic array to make reference to icons like this:
{name: "text", avatar: srcs[15]}
This works great, but now I dynamically create an array from my json api and it gives me array of objects like this:
{name: "text", avatar: "srcs[15]"}
so I cannot reference to my avatars now. How can I remove double quotes to get my array work again?
Please note that I don't want to get the srcs[15] value to the array, just make a reference to the source array.
The JSON data format does not support references. What you want it not possible.
You need to either:
Put the data you want there explicitly (this may involve duplication) or
Describe the relationship in a way that the program consuming the JSON can interpret as a reference. You could use the reviver argument of JSON.parse to inflate the description back to the data you want to point it to.
JSON is self-contained static data, and it can't reference named variables or objects outside of its own structure.
You can do it like this instead:
{ "name": "text", "avatarIndex": 15 }
And then do one of these to use it:
var avatar = srcs[data.avatarIndex]; // Avatar object in separate variable
// or
data.avatar = srcs[data.avatarIndex]; // Avatar object added into data
You should just put either the value or the whole array , you have also to read about what format json support here
Here's my suggested solutions
var array = [1, 2, 3, 4, 5, 6]
var json1 = {
name: 'test',
value: array
}
console.log("solution 1 :" + json1.value[2])
var json2 = {
name: 'test',
value: array[2]
}
console.log("solution 2 :" + json2.value)
I have a little problem in picking up the data from the JSON actually can get some data, however when you have the occurrence of "/_string" the script error.
example:
JSON
"results":[{
price_value_prices: 15.05
price_value_prices/_currency: "USD"
price_value_prices/_source: "$15.05"
}];
AJAX
$.ajax({
type: 'GET',
url: $url,
dataType: 'json',
success: function (data) {
data.results[$n].price_value_prices/_sources
}
});
console log output
_sources is not defined
how can I solve this problem?
First thing, your JSON is invalid without the quotes on the left side for the field names, so change it to:
"results":[{
"price_value_prices": 15.05
"price_value_prices/_currency": "USD"
"price_value_prices/_source": "$15.05"
}]
And then access it using the [] operator.
data.results[$n]["price_value_prices/_sources"]
You cannot use / because it is another operator. If you have / or . in your field names, it is wise to use the [] operator.
Your JSON is invalid in four different ways:
You have a property initializer outside of any object initializer.
Property keys must be in double quotes in JSON.
You must have commas between properties in an object.
You have a ; at the end of it.
#2 would solve your / problem.
Here's a valid version:
{
"results": [{
"price_value_prices": 15.05,
"price_value_prices/_currency": "USD",
"price_value_prices/_source": "$15.05"
}]
}
Assuming you parse that and assign the result to obj, you can access price_value_prices/_currency using brackets notation and quotes (any kind):
console.log(obj.results[0]["price_value_prices/_currency"]);
console.log(obj.results[0]['price_value_prices/_currency']);
Note the [0] after results, since it's an array with a single entry in it.
I have JavaScript JSON data:
var data = '{a: 10, b: 20}'
I want to convert it to Python JSON. How can I do?
My situation:
I have script that read text from a website. website has data in javascript variables like I show in example. I extracted variable part '{a: 10, b: 20}'. But for the python, it is still string format. I need to convert that data into Python JSON so I can do further work.
How can I convert JavaScript JSON to Python JSON?
Python JSON is a bit of a misnomer as JSON (as in JavaScript Object Notation) is a subset of JavaScript and simply describes a JavaScript object. It is an exchange format that does not depend on the language you are using it with.
You can use the json module to parse JSON in Python, and return an equivalent Python object.
it need regex replace before can convert it json
import re
import json
data = '''{a: 10, b: true, c :"string", "d" : jsVariable, e:'single'}'''
# replace single with double quote
data = data.replace("'", '"')
# wrap key with double quotes
data = re.sub(r"(\w+)\s?:", r'"\1":', data)
# wrap value with double quotes
# but not for interger or boolean
data = re.sub(r":\s?(?!(\d+|true|false))(\w+)", r':"\2"', data)
data = json.loads(data)
print(data['a']) # 10
print(json.dumps(data, indent=2)) # formatted json string
Apparently some libraries like RSON can help you.
According to that answer
var data = '{a: 10, b: 20}' is not a valid JSON. It is valid JavaScript
If you were to do
var data = JSON.stringify({ a: 10, b: 20 });
you would find it actually becomes
var data = '{ "a": 10, "b": 20 }'
The extra " around the a and b variables being the part that makes this valid JSON. The confusion comes from the fact that JavaScript is more forgiving than JSON.
Don't feel bad. You will not be the only one who will fall into this trap.
I can only send string or numeric values,how to send an array?
You'll probably get a slew of answers all saying "JSON".
Here are some case specific examples. 'data' holds what you send.
var numArray = [17, 42, 23];
data = '[' + numArray + ']';
var strArray = ['foo', 'bar', 'baz'];
data = '["' + numArray.join('", "') + '"]';
For the general case, use a function that recursively encodes objects to JSON. If you really want me to, I'll post an example implementation, but it's a fun project so you might want to give it a try. If you're using a Javascript library, it might have a JSON encoder of it's own (such as jQuery's serializeArray).
There's are no built-in JSON serializers in javascript so you will need to use a library. A good one is json2.js.
Here's a sample:
// suppose you have an array of some objects:
var array = [{ prop1: 'value1', prop2: 10 }, { prop1: 'value2', prop2: 20 }];
// convert it to json string:
var jsonString = JSON.stringify(array);
// TODO: send the jsonString variable as a parameter in an ajax request
// On the server side you will need a JSON deserializer
// to convert values back to an array of objects
I can only send string or numeric values
Actually you can only send strings. When you include a number it is just turned into a string; it's up to the server-side script to parse that back into a number if it wants to.
how to send an array?
The native HTML-forms way of sending multiple values is using multiple inputs. You can reproduce this by including the same named parameter multiple times. To send [1,2,3]:
http://www.example.com/ajax.script?a=1&a=2&a=3
The same multiple-parameter-instance query string can be sent in an AJAX post request.
If you are using a higher-level framework to create the form-encoded string, it depends on the framework how it accepts multiple parameter instances. For example with jQuery you can post an object like {a: [1,2,3]}.
The other way is to forget the standard HTML form encoding and just pass all your values in whatever special encoding you like that allows you to retain datatypes and structure. Usually this would be JavaScript value literals (JSON):
http://www.example.com/ajax.script?a=%5B1%2C2%2C3%D
(that is, [1,2,3], URL-encoded.) You then need a JSON parser on the server to recreate native array values there.
You can actually send Arrays in a much cleaner way instead of trying to encoding JSON.
For example, this works
$.post("yourapp.php", { 'data[]': ["iphone", "galaxy"] });
See http://api.jquery.com/jQuery.post/ for more.