JSON parse fails when there are regular expressions - json

I am trying to parse a mongodb query in json to dictionary and the JObject.Parse throws exception.
The JSON string is something like below
{ vendor: "xyx", product: { $in : [ /prod1/i, /prod2/i, /prod3/i ] } }
The exception is message is
Error parsing comment. Expected: *, got p. Path 'product.$in', line 1, position 50.

JSON doesn't have support for regular expressions but you could change your JSON string to use the $regex query operator syntax instead:
{ vendor: "xyx", product: { $in: [
{$regex: "prod1", $options: "i"},
{$regex: "prod2", $options: "i"},
{$regex: "prod3", $options: "i"}
] } }
All in one string, of course. And to be valid JSON, the keys all need to be quoted too, but JObject.Parse may allow them to be omitted as it doesn't sound like that part was giving you trouble.

Looks like you didn't mean to say JSON, but rather MongoDB, no?
For MongoDB queries, you need to do this:
{ vendor: "xyx", product: { $in : [ Pattern.compile(/prod1/i), Pattern.compile(/prod2/i), Pattern.compile(/prod3/i) ] } }

Related

How to send multiple query variables using GraphQL Playground

If I have one variable named $external and one named $manifest, which should be JSON, how do I define them both as query variables in the GraphQL Playground?
{
"external": "name",
"manifest":
{
"some": "json",
}
}
This gives me an error: Expected String but found }``.
Yes, I am on the query variables tab, something that has caught out many people asking about how to pass a single query variable.
Avoid trailing commas in JSON (line 5 and originally line 6 as well)
{
"external": "name",
"manifest": {
"some": "json"
}
}
is valid JSON
You can test your JSON using jsonlint

Сonvert dict or json formats with nested objects into string

Now I have a string in format dict but as i can guess its a json format its look like:
{
"gid":"1201400250397201",
"memberships":[
"can be nested objects",
...
],
"name":"Name of task",
"parent":{
"gid":"1201400250397199",
"name":"name of parent task"
},
"permalink_url":"https://url...."
}
So first question: am i right? I used dumps() from json library but got unicode escape sequences, loads() didnt work for me, i got error "the JSON object must be str, bytes or bytearray, not dict".
Second question: if its not json format, how can i get comfortable view? I did it:
first of all i get dict-line, then I print a dictionary's key:
for key in task:
task
print(task[key])
output:
1201400250397201
[]
Name of task
{'gid': '1201400250397199', 'name': ''name of parent task'}
https://url....
At actually it would be great if I get something like that:
gid: 1201400250397201
name: Name of task
parent_name: 'Name of task' etc
But I dont know how to get it :(
Next question: as you can see for part "parent" (penultimate line) I also get dictionary, how can I extract it and get convenient format?
Or maybe you have your comfortable methods?
Like stated in your error, the object you are working with is already a dictionary. You can print it directly as json with json.dumps:
task = {'gid': '1201400250397201', 'memberships': [{}], 'name': 'Name of task', 'parent': {'gid': '1201400250397199', 'name': 'name of parent task'},'permalink_url': 'https://url....'}
print(json.dumps(task, indent=4))
Setting indent=4 makes it readable and you'll get:
{
"gid": "1201400250397201",
"memberships": [
{}
],
"name": "Name of task",
"parent": {
"gid": "1201400250397199",
"name": "name of parent task"
},
"permalink_url": "https://url...."
}
If you don't want unicode characters to be escaped, add the argument ensure_ascii=False:
print(json.dumps(task, indent=4, ensure_ascii=False))

Sorting Nested JSON in Python

Is it possible to sort the following kind of nested JSON in python3 based on the Key "age"
{
"barcelona":[
{
"age":29,
"name":"john"
}
],
"london":[
{
"age":23,
"name":"bob"
}
],
"mancherster":[
{
"age":23,
"name":"shaw"
}
],
"paris":[
{
"age":45,
"name":"bony"
},
{
"age":16,
"name":"paul"
}
]
}
Thanks in advance for your responses
I suppose you just want to sort the lists for each city? In that case this should work:
import json
json_str = "<your json string>"
json_obj = json.loads(json_str)
by_age = { key: sorted(value, key=lambda v: v['age']) for key, value in json_obj.items() }
Btw, there are errors in the JSON you posted - trailing commas (the commas at the end of "name": "whatever", in this case) are not allowed. You need to remove them to avoid an error at the json.loads call.

Dynamically build json using groovy

I am trying to dynamically build some json based on data I retrieve from a database. Up until the opening '[' is the "root" I guess you could say. The next parts with name and value are dynamic and will be based on the number of results I get from the db. I query the db and then the idea was to iterate through the result adding to the json. Can I use jsonBuilder for the root section and then loop with jsonSlurper to add each additional section? Most of the examples I have seen deal with a root and then a one time "slurp" and then joining the two so wasn't sure if I should try a different method for looping and appending multiple sections.
Any tips would be greatly appreciated. Thanks.
{
"hostname": "$hostname",
"path": "$path",
"extPath": "$extPath",
"appName": "$appName",
"update": {"parameter": [
{
"name": "$name",
"value": "$value"
},
{
"name": "$name",
"value": "$value"
}
]}
}
EDIT: So what I ended up doing was just using StringBuilder to create the initial block and then append the subsequent sections. Maybe not the most graceful way to do it, but it works!
//Create the json string
StringBuilder json = new StringBuilder("""{
"hostname": "$hostname",
"path": "$path",
"extPath": "$extPath",
"appName": "$appName",
"update": {"parameter": ["""
)
//Append
sql.eachRow("""<query>""",
{ params ->
json.append("""{ "name": "params.name", "value": "params.value" },""");
}
)
//Add closing json tags
json.append("""]}}""")
If I got your explanation correctly and if the data is not very big (it can live in memory), I'd build a Map object (which is very easy to work with in groovy) and convert it to JSON afterwards. Something like this:
def data = [
hostname: hostname,
path: path,
extPath: extPath,
appName: appName,
update: [parameter: []]
]
sql.eachRow(sqlStr) { row ->
data.update.parameter << [name: row.name, value: row.value]
}
println JsonOutput.toJson(data)
If you're using Grails and Groovy you can utilize grails.converters.JSON.
First, define a JSON named config:
JSON.createNamedConfig('person') {
it.registerObjectMarshaller(Person) {
Person person ->
def output = [:]
output['name'] = person.name
output['address'] = person.address
output['age'] = person.age
output
}
}
This will result in a statically defined named configuration for the Object type of person. Now, you can simply call:
JSON.use('person') {
Person.findAll() as JSON
}
This will return every person in the database with their name, address and age all in one JSON request. I don't know if you're using grails as well in this situation though, for pure Groovy go with another answer here.

Scala Json(json4s) parse return None

$ "properties": [
{
"name": "Armour",
"values": [
[
"258",
1
]
],
"displayMode": 0
},...]
I have this JSON array.
I use json4s and scala for parse this code.
case class Property(
name: String,
values: Option[Option[(String, Int)]] = None,
displayMode: Int
)
I write case class for this block, but I get "None" when get values...
I need get "258" in this example. What am I doing wrong?
Your Json looks like you have a list of lists under your values property. I guess you want to have something like dictionary which should be with curly brackets instead of just brackets. Other thing is why would you parse that into Option[Option[(String, Int)]]? Try defining that as optional Map[String, Int].
Could this work?
values: List[(String, Int)] = Nil